public MDFeRetorno encerramento(final String chaveAcesso, final String numeroProtocolo,
            final String codigoMunicipio, final LocalDate dataEncerramento, final DFUnidadeFederativa unidadeFederativa) throws Exception {
        return this.wsEncerramento.encerraMdfe(chaveAcesso, numeroProtocolo, codigoMunicipio, dataEncerramento, unidadeFederativa);
    }

public MDFeRetorno encerramento ( final String chaveAcesso , final String numeroProtocolo , final String codigoMunicipio , final LocalDate dataEncerramento , final DFUnidadeFederativa unidadeFederativa ) throws Exception { return this . wsEncerramento . encerraMdfe ( chaveAcesso , numeroProtocolo , codigoMunicipio , dataEncerramento , unidadeFederativa ) ; }

Faz o encerramento do MDFe

@param chaveAcesso chave de acesso da nota
@param numeroProtocolo numero do protocolo da nota
@param codigoMunicipio Informar o código do município do encerramento do manifesto
@param dataEncerramento Data em que o manifesto foi encerrado.
@param unidadeFederativa Informar a UF de encerramento do manifesto
@return dados do encerramento da nota retornado pelo webservice
@throws Exception caso nao consiga gerar o xml ou problema de conexao com o sefaz


public MDFeRetorno encerramentoAssinado(final String chaveAcesso, final String eventoAssinadoXml) throws Exception {
        return this.wsEncerramento.encerramentoMdfeAssinado(chaveAcesso, eventoAssinadoXml);
    }

public MDFeRetorno encerramentoAssinado ( final String chaveAcesso , final String eventoAssinadoXml ) throws Exception { return this . wsEncerramento . encerramentoMdfeAssinado ( chaveAcesso , eventoAssinadoXml ) ; }

Faz o encerramento do MDFe assinado

@param chaveAcesso
@param eventoAssinadoXml
@return
@throws Exception


public void receiveResultmdfeStatusServicoMDF(
            com.fincatto.documentofiscal.mdfe3.webservices.statusservico.MDFeStatusServicoStub.MdfeStatusServicoMDFResult result
    ) {
    }

public void receiveResultmdfeStatusServicoMDF ( com . fincatto . documentofiscal . mdfe3 . webservices . statusservico . MDFeStatusServicoStub . MdfeStatusServicoMDFResult result ) { }

auto generated Axis2 call back method for mdfeStatusServicoMDF method
override this method for handling normal response from mdfeStatusServicoMDF operation


private OMElement efetuaConsultaStatusBahia(final OMElement omElement) throws RemoteException {
        final NfeStatusServicoStub.NfeCabecMsg cabec = new NfeStatusServicoStub.NfeCabecMsg();
        cabec.setCUF(DFUnidadeFederativa.BA.getCodigoIbge());
        cabec.setVersaoDados(this.config.getVersao());

        final NfeStatusServicoStub.NfeCabecMsgE cabecEnv = new NfeStatusServicoStub.NfeCabecMsgE();
        cabecEnv.setNfeCabecMsg(cabec);

        final NfeStatusServicoStub.NfeDadosMsg dados = new NfeStatusServicoStub.NfeDadosMsg();
        dados.setExtraElement(omElement);

        final NFAutorizador31 autorizador = NFAutorizador31.valueOfCodigoUF(DFUnidadeFederativa.BA);
        final String endpoint = autorizador.getNfeStatusServico(this.config.getAmbiente());
        if (endpoint == null) {
            throw new IllegalArgumentException("Nao foi possivel encontrar URL para StatusServico " + DFModelo.NFE.name() + ", autorizador " + autorizador.name() + ", UF " + DFUnidadeFederativa.BA.name());
        }

        return new NfeStatusServicoStub(endpoint).nfeStatusServicoNF(dados, cabecEnv).getExtraElement();
    }

este metodo teve que ser implementado pois a Bahia trata de forma diferente


public static float[] computeUpdatedXu(Solver solver,
                                         double value,
                                         float[] Xu,
                                         float[] Yi,
                                         boolean implicit) {
    if (Yi == null) {
      return null;
    }

    boolean noXu = Xu == null;
    double Qui = noXu ? 0.0 : VectorMath.dot(Xu, Yi);
    // Qui' is the target, new value of Qui
    // 0.5 reflects a "don't know" state
    double targetQui = computeTargetQui(implicit, value, noXu ? 0.5 : Qui);
    if (Double.isNaN(targetQui)) {
      return null;
    }

    double dQui = targetQui - Qui;
    double[] dQuiYi = new double[Yi.length];
    for (int i = 0; i < dQuiYi.length; i++) {
      dQuiYi[i] = Yi[i] * dQui;
    }
    double[] dXu = solver.solveDToD(dQuiYi);

    float[] newXu = noXu ? new float[dXu.length] : Xu.clone();
    for (int i = 0; i < newXu.length; i++) {
      newXu[i] += dXu[i];
    }
    return newXu;
  }

public
static
float
[
]
computeUpdatedXu
(
Solver
solver
,
double
value
,
float
[
]
Xu
,
float
[
]
Yi
,
boolean
implicit
)
{
if
(
Yi
==
)
{
return
;
}
boolean
noXu
=
Xu
==
;
double
Qui
=
noXu
0.0
:
VectorMath
.
dot
(
Xu
,
Yi
)
;
// Qui' is the target, new value of Qui
// 0.5 reflects a "don't know" state
double
targetQui
=
computeTargetQui
(
implicit
,
value
,
noXu
0.5
:
Qui
)
;
if
(
Double
.
isNaN
(
targetQui
)
)
{
return
;
}
double
dQui
=
targetQui
Qui
;
double
[
]
dQuiYi
=
new
double
[
Yi
.
length
]
;
for
(
int
i
=
0
;
i
<
dQuiYi
.
length
;
i
++
)
{
dQuiYi
[
i
]
=
Yi
[
i
]
*
dQui
;
}
double
[
]
dXu
=
solver
.
solveDToD
(
dQuiYi
)
;
float
[
]
newXu
=
noXu
new
float
[
dXu
.
length
]
:
Xu
.
clone
(
)
;
for
(
int
i
=
0
;
i
<
newXu
.
length
;
i
++
)
{
newXu
[
i
]
+=
dXu
[
i
]
;
}
return
newXu
;
}

Computes how a user vector Xu changes in response to interaction with an item vector Yi.
This can also be used to compute how an item vector changes in response to a user interaction,
even though the code naming follows the former convention.

@param solver solver helping solve for Xu in Qu*Y = Xu * (Yt * Y)
@param value strength of interaction
@param Xu current user vector (null if no existing user vector)
@param Yi current item vector
@param implicit whether the model is implicit feedback
@return new user vector Xu, or {@code null} if no update should be made (i.e. there was no
item vector; the update would push the new Qui farther out of range)

Computes how a user vector Xu changes in response to interaction with an item vector Yi . This can also be used to compute how an item vector changes in response to a user interaction even though the code naming follows the former convention .


public static double cosineSimilarity(float[] x, float[] y, double normY) {
    int length = x.length;
    double dot = 0.0;
    double totalXSq = 0.0;
    for (int i = 0; i < length; i++) {
      double xi = x[i];
      totalXSq += xi * xi;
      dot += xi * y[i];
    }
    return dot / (Math.sqrt(totalXSq) * normY);
  }

public static double cosineSimilarity ( float [ ] x , float [ ] y , double normY ) { int length = x . length ; double dot = 0.0 ; double totalXSq = 0.0 ; for ( int i = 0 ; i < length ; i ++ ) { double xi = x [ i ] ; totalXSq += xi * xi ; dot += xi * y [ i ] ; } return dot / ( Math . sqrt ( totalXSq ) * normY ) ; }

Computes cosine similarity of values in two given arrays, when the norm of one array is
known in advance, which is a not-uncommon case.

@param x one array
@param y the other array
@param normY norm of y
@return cosine similarity = dot(x,y) / (norm(x) * norm(y))

Computes cosine similarity of values in two given arrays when the norm of one array is known in advance which is a not - uncommon case .


public void compute() {
    // Make sure only one attempts to build at one time
    if (solverUpdating.compareAndSet(false, true)) {
      executor.execute(LoggingCallable.log(() -> {
        try {
          log.info("Computing cached solver");
          // Not as much hurry if one already exists
          boolean lowPriority = solver.get() != null;
          Solver newYTYSolver = LinearSystemSolver.getSolver(vectorPartitions.getVTV(lowPriority));
          if (newYTYSolver != null) {
            log.info("Computed new solver {}", newYTYSolver);
            solver.set(newYTYSolver);
          }
        } finally {
          // Allow any threads waiting for initial model to proceed.
          // It's possible the solver is still null here if there is no input.
          solverInitialized.countDown();
          solverUpdating.set(false);
        }
      }).asRunnable());
    }
  }

Proactively try to compute the solver asynchronously, if not already computed.
Does not block.

Proactively try to compute the solver asynchronously if not already computed . Does not block .


public static void deleteRecursively(Path rootDir) throws IOException {
    if (rootDir == null || !Files.exists(rootDir)) {
      return;
    }
    Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Files.delete(file);
        return FileVisitResult.CONTINUE;
      }
      @Override
      public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        Files.delete(dir);
        return FileVisitResult.CONTINUE;
      }
    });
  }

public static void deleteRecursively ( Path rootDir ) throws IOException { if ( rootDir == null || ! Files . exists ( rootDir ) ) { return ; } Files . walkFileTree ( rootDir , new SimpleFileVisitor < Path > ( ) { @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { Files . delete ( file ) ; return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult postVisitDirectory ( Path dir , IOException exc ) throws IOException { Files . delete ( dir ) ; return FileVisitResult . CONTINUE ; } } ) ; }

Deletes the given path, and if it is a directory, all files and subdirectories within it.

@param rootDir directory to delete
@throws IOException if any error occurs while deleting files or directories

Deletes the given path and if it is a directory all files and subdirectories within it .


public static <T> T loadInstanceOf(String implClassName,
                                     Class<T> superClass,
                                     Class<?>[] constructorTypes,
                                     Object[] constructorArgs) {
    try {
      Class<? extends T> configClass = loadClass(implClassName, superClass);
      Constructor<? extends T> constructor = configClass.getConstructor(constructorTypes);
      return constructor.newInstance(constructorArgs);
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) {
      throw new IllegalArgumentException("No valid " + superClass + " binding exists", e);
    } catch (InvocationTargetException ite) {
      throw new IllegalStateException("Could not instantiate " + superClass + " due to exception",
                                      ite.getCause());
    }
  }

public
static
<
T
>
T
loadInstanceOf
(
String
implClassName
,
Class
<
T
>
superClass
,
Class
<
>
[
]
constructorTypes
,
Object
[
]
constructorArgs
)
{
try
{
Class
<
extends
T
>
configClass
=
loadClass
(
implClassName
,
superClass
)
;
Constructor
<
extends
T
>
constructor
=
configClass
.
getConstructor
(
constructorTypes
)
;
return
constructor
.
newInstance
(
constructorArgs
)
;
}
catch
(
NoSuchMethodException
|
InstantiationException
|
IllegalAccessException
e
)
{
throw
new
IllegalArgumentException
(
"No valid "
+
superClass
+
" binding exists"
,
e
)
;
}
catch
(
InvocationTargetException
ite
)
{
throw
new
IllegalStateException
(
"Could not instantiate "
+
superClass
+
" due to exception"
,
ite
.
getCause
(
)
)
;
}
}

Loads and instantiates a named implementation class, a subclass of a given supertype,
whose constructor takes the given arguments.

@param implClassName implementation class name
@param superClass superclass or interface that the implementation extends
@param constructorTypes argument types of constructor to use
@param constructorArgs actual constructor arguments
@param <T> type of returned instance
@return instance of {@code implClassName}

Loads and instantiates a named implementation class a subclass of a given supertype whose constructor takes the given arguments .


public void publishAdditionalModelData(JavaSparkContext sparkContext,
                                         PMML pmml,
                                         JavaRDD<M> newData,
                                         JavaRDD<M> pastData,
                                         Path modelParentPath,
                                         TopicProducer<String, String> modelUpdateTopic) {
    // Do nothing by default
  }

public
void
publishAdditionalModelData
(
JavaSparkContext
sparkContext
,
PMML
pmml
,
JavaRDD
<
M
>
newData
,
JavaRDD
<
M
>
pastData
,
Path
modelParentPath
,
TopicProducer
<
String
,
String
>
modelUpdateTopic
)
{
// Do nothing by default
}

Optionally, publish additional model-related information to the update topic,
after the model has been written. This is needed only in specific cases, like the
ALS algorithm, where the model serialization in PMML can't contain all of the info.

@param sparkContext active Spark Context
@param pmml model for which extra data should be written
@param newData data that has arrived in current interval
@param pastData all previously-known data (may be {@code null})
@param modelParentPath directory containing model files, if applicable
@param modelUpdateTopic message topic to write to

Optionally publish additional model - related information to the update topic after the model has been written . This is needed only in specific cases like the ALS algorithm where the model serialization in PMML can t contain all of the info .


public void openCustomTab(
            final Context context,
            final CustomTabsIntent customTabsIntent,
            final Uri uri,
            CustomTabFallback fallback) {
        final String packageName = getPackageNameToUse(context);

        if (packageName != null) {
            final CustomTabsServiceConnection connection = new CustomTabsServiceConnection() {
                @Override
                public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient client) {
                    client.warmup(0L); // This prevents backgrounding after redirection

                    customTabsIntent.intent.setPackage(packageName);
                    customTabsIntent.intent.setData(uri);
                    customTabsIntent.launchUrl(context, uri);
                }
                @Override
                public void onServiceDisconnected(ComponentName name) {}
            };
            CustomTabsClient.bindCustomTabsService(context, packageName, connection);
        } else if (fallback != null) {
            fallback.openUri(context, uri);
        } else {
            Log.e(UberSdk.UBER_SDK_LOG_TAG,
                    "Use of openCustomTab without Customtab support or a fallback set");
        }
    }

Opens the URL on a Custom Tab if possible. Otherwise fallsback to opening it on a WebView.

@param context The host context.
@param customTabsIntent a CustomTabsIntent to be used if Custom Tabs is available.
@param uri the Uri to be opened.
@param fallback a CustomTabFallback to be used if Custom Tabs is not available.

Opens the URL on a Custom Tab if possible . Otherwise fallsback to opening it on a WebView .


@Nullable
    public String getPackageNameToUse(Context context) {
        if (packageNameToUse != null) return packageNameToUse;

        PackageManager pm = context.getPackageManager();
        // Get default VIEW intent handler.
        Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));
        ResolveInfo defaultViewHandlerInfo = pm.resolveActivity(activityIntent, 0);
        String defaultViewHandlerPackageName = null;
        if (defaultViewHandlerInfo != null) {
            defaultViewHandlerPackageName = defaultViewHandlerInfo.activityInfo.packageName;
        }

        // Get all apps that can handle VIEW intents.
        List<ResolveInfo> resolvedActivityList = pm.queryIntentActivities(activityIntent, 0);
        List<String> packagesSupportingCustomTabs = new ArrayList<>();
        for (ResolveInfo info : resolvedActivityList) {
            Intent serviceIntent = new Intent();
            serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
            serviceIntent.setPackage(info.activityInfo.packageName);
            if (pm.resolveService(serviceIntent, 0) != null) {
                packagesSupportingCustomTabs.add(info.activityInfo.packageName);
            }
        }

        // Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents
        // and service calls.
        if (packagesSupportingCustomTabs.isEmpty()) {
            packageNameToUse = null;
        } else if (packagesSupportingCustomTabs.size() == 1) {
            packageNameToUse = packagesSupportingCustomTabs.get(0);
        } else if (!TextUtils.isEmpty(defaultViewHandlerPackageName)
                && !hasSpecializedHandlerIntents(context, activityIntent)
                && packagesSupportingCustomTabs.contains(defaultViewHandlerPackageName)) {
            packageNameToUse = defaultViewHandlerPackageName;
        } else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE)) {
            packageNameToUse = STABLE_PACKAGE;
        } else if (packagesSupportingCustomTabs.contains(BETA_PACKAGE)) {
            packageNameToUse = BETA_PACKAGE;
        } else if (packagesSupportingCustomTabs.contains(DEV_PACKAGE)) {
            packageNameToUse = DEV_PACKAGE;
        } else if (packagesSupportingCustomTabs.contains(LOCAL_PACKAGE)) {
            packageNameToUse = LOCAL_PACKAGE;
        }
        return packageNameToUse;
    }

Goes through all apps that handle VIEW intents and have a warmup service. Picks
the one chosen by the user if there is one, otherwise makes a best effort to return a
valid package name.

This is not threadsafe.

@param context {@link Context} to use for accessing {@link PackageManager}.
@return The package name recommended to use for connecting to custom tabs related components.

Goes through all apps that handle VIEW intents and have a warmup service . Picks the one chosen by the user if there is one otherwise makes a best effort to return a valid package name .


private boolean hasSpecializedHandlerIntents(Context context, Intent intent) {
        try {
            PackageManager pm = context.getPackageManager();
            List<ResolveInfo> handlers = pm.queryIntentActivities(
                    intent,
                    PackageManager.GET_RESOLVED_FILTER);
            if (handlers == null || handlers.size() == 0) {
                return false;
            }
            for (ResolveInfo resolveInfo : handlers) {
                IntentFilter filter = resolveInfo.filter;
                if (filter == null) continue;
                if (filter.countDataAuthorities() == 0 || filter.countDataPaths() == 0) continue;
                if (resolveInfo.activityInfo == null) continue;
                return true;
            }
        } catch (RuntimeException e) {
            Log.e(TAG, "Runtime exception while getting specialized handlers");
        }
        return false;
    }

Used to check whether there is a specialized handler for a given intent.
@param intent The intent to check with.
@return Whether there is a specialized handler for the given intent.

Used to check whether there is a specialized handler for a given intent .


private void load() {
        AccessToken accessToken = accessTokenStorage.getAccessToken();

        if (accessToken != null) {
            AccessTokenSession session = new AccessTokenSession(sessionConfiguration,
                    accessTokenStorage);
            rideRequestView.setSession(session);

            loadRideRequestView();
        } else {
            login();
        }
    }

private void load ( ) { AccessToken accessToken = accessTokenStorage . getAccessToken ( ) ; if ( accessToken != null ) { AccessTokenSession session = new AccessTokenSession ( sessionConfiguration , accessTokenStorage ) ; rideRequestView . setSession ( session ) ; loadRideRequestView ( ) ; } else { login ( ) ; } }

Loads the appropriate view in the activity based on whether user is successfully authorized or not.

Loads the appropriate view in the activity based on whether user is successfully authorized or not .


public void execute() {
        final CustomTabsIntent intent = new CustomTabsIntent.Builder().build();
        customTabsHelper.openCustomTab(context, intent, uri, new CustomTabsHelper.BrowserFallback());
    }

public void execute ( ) { final CustomTabsIntent intent = new CustomTabsIntent . Builder ( ) . build ( ) ; customTabsHelper . openCustomTab ( context , intent , uri , new CustomTabsHelper . BrowserFallback ( ) ) ; }

Executes the deeplink to launch the Uber app.  If the app is not installed redirects to the play store.

Executes the deeplink to launch the Uber app . If the app is not installed redirects to the play store .


private void validateConfiguration(SessionConfiguration configuration) {
        String nullError = "%s must not be null";
        String sampleError = "Please update your %s in the gradle.properties of the project before " +
                "using the Uber SDK Sample app. For a more secure storage location, " +
                "please investigate storing in your user home gradle.properties ";

        checkNotNull(configuration, String.format(nullError, "SessionConfiguration"));
        checkNotNull(configuration.getClientId(), String.format(nullError, "Client ID"));
        checkNotNull(configuration.getRedirectUri(), String.format(nullError, "Redirect URI"));
        checkState(!configuration.getClientId().equals("insert_your_client_id_here"),
                String.format(sampleError, "Client ID"));
        checkState(!configuration.getRedirectUri().equals("insert_your_redirect_uri_here"),
                String.format(sampleError, "Redirect URI"));
    }

Validates the local variables needed by the Uber SDK used in the sample project
@param configuration


public static Intent newResponseIntent(Context context, Uri responseUri) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.setData(responseUri);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return intent;
    }

public static Intent newResponseIntent ( Context context , Uri responseUri ) { Intent intent = new Intent ( context , LoginActivity . class ) ; intent . setData ( responseUri ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP | Intent . FLAG_ACTIVITY_SINGLE_TOP ) ; return intent ; }

Used to handle Redirect URI response from customtab or browser

@param context
@param responseUri
@return


public boolean editMap(ConfigurationHandler configurationHandler) {
        String method = configurationHandler.getMethod().toUpperCase();

        if (configurationHandlerMap.containsKey(Method.valueOf(method))) {
            configurationHandlerMap.put(Method.valueOf(method), configurationHandler);

            return true;
        }

        return false;
    }

public boolean editMap ( ConfigurationHandler configurationHandler ) { String method = configurationHandler . getMethod ( ) . toUpperCase ( ) ; if ( configurationHandlerMap . containsKey ( Method . valueOf ( method ) ) ) { configurationHandlerMap . put ( Method . valueOf ( method ) , configurationHandler ) ; return true ; } return false ; }

Edit representation for method specified in sent parameter after controller calls for it.
@param configurationHandler Our representation of response.
@return True if mock-service contains sent method, false otherwise.

Edit representation for method specified in sent parameter after controller calls for it .


public static void main(String[] args) {
        if(args.length!=1) {
            System.err.println("Must provide one argument - Mesos master location string");
            System.exit(1);
        }
        int numTasks=10;
        int numIters=5;
        BlockingQueue<TaskRequest> taskQueue = new LinkedBlockingQueue<>();
        final TaskGenerator taskGenerator = new TaskGenerator(taskQueue, numIters, numTasks);
        final SampleFramework framework = new SampleFramework(taskQueue, args[0], // mesos master location string
                new Action1<String>() {
                    @Override
                    public void call(String s) {
                        taskGenerator.tasksCompleted.incrementAndGet();
                    }
                },
                new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        return "sleep 2";
                    }
                });
        long start = System.currentTimeMillis();
        (new Thread(taskGenerator)).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                framework.runAll();
            }
        }).start();
        while(taskGenerator.tasksCompleted.get() < (numIters*numTasks)) {
            System.out.println("NUM TASKS COMPLETED: " + taskGenerator.tasksCompleted.get() + " of " + (numIters*numTasks));
            try{Thread.sleep(1000);}catch(InterruptedException ie){}
        }
        System.out.println("Took " + (System.currentTimeMillis()-start) + " mS to complete " + (numIters*numTasks) + " tasks");
        framework.shutdown();
        System.exit(0);
    }

Main method to run the task generator.
@param args Arguments to the program. Provide as the only argument, the mesos connection string.


public void shutdown() {
        System.out.println("Stopping down mesos driver");
        Protos.Status status = mesosSchedulerDriver.stop();
        isShutdown.set(true);
    }

public
void
shutdown
(
)
{
System
.
out
.
println
(
"Stopping down mesos driver"
)
;
Protos
.
Status
status
=
mesosSchedulerDriver
.
stop
(
)
;
isShutdown
.
set
(
true
)
;
}


@Override
    public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
        Collection<TaskRequest> runningTasks = targetVM.getRunningTasks();
        if(runningTasks!=null && !runningTasks.isEmpty())
            return new Result(false, "Already has " + runningTasks.size() + " tasks running on it");
        Collection<TaskAssignmentResult> tasksCurrentlyAssigned = targetVM.getTasksCurrentlyAssigned();
        if(tasksCurrentlyAssigned!=null && !tasksCurrentlyAssigned.isEmpty())
            return new Result(false, "Already has " + tasksCurrentlyAssigned.size() + " assigned on it");
        return new Result(true, "");
    }

@
Override
public
Result
evaluate
(
TaskRequest
taskRequest
,
VirtualMachineCurrentState
targetVM
,
TaskTrackerState
taskTrackerState
)
{
Collection
<
TaskRequest
>
runningTasks
=
targetVM
.
getRunningTasks
(
)
;
if
(
runningTasks
!=
&&
!
runningTasks
.
isEmpty
(
)
)
return
new
Result
(
false
,
"Already has "
+
runningTasks
.
size
(
)
+
" tasks running on it"
)
;
Collection
<
TaskAssignmentResult
>
tasksCurrentlyAssigned
=
targetVM
.
getTasksCurrentlyAssigned
(
)
;
if
(
tasksCurrentlyAssigned
!=
&&
!
tasksCurrentlyAssigned
.
isEmpty
(
)
)
return
new
Result
(
false
,
"Already has "
+
tasksCurrentlyAssigned
.
size
(
)
+
" assigned on it"
)
;
return
new
Result
(
true
,
""
)
;
}

Determines whether the prospective host already has tasks either running on it or assigned to be run on
it, and returns a false Result if either of those things is the case.

@param taskRequest      describes the task to be considered for assignment to the host
@param targetVM         describes the host to be considered for accepting the task
@param taskTrackerState describes the state of tasks assigned to or running on hosts throughout the
system
@return an unsuccessful Result if the target already has running tasks or assigned tasks, or a successful
Result otherwise

Determines whether the prospective host already has tasks either running on it or assigned to be run on it and returns a false Result if either of those things is the case .


@Override
    public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
        String targetHostAttrVal = getAttrValue(targetVM.getCurrAvailableResources());
        if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) {
            return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname());
        }
        String requiredAttrVal = hostAttributeValueGetter.call(taskRequest.getId());
        return targetHostAttrVal.equals(requiredAttrVal)?
                new Result(true, "") :
                new Result(false, "Host attribute " + hostAttributeName + ": required=" + requiredAttrVal + ", got=" + targetHostAttrVal);
    }

@
Override
public
Result
evaluate
(
TaskRequest
taskRequest
,
VirtualMachineCurrentState
targetVM
,
TaskTrackerState
taskTrackerState
)
{
String
targetHostAttrVal
=
getAttrValue
(
targetVM
.
getCurrAvailableResources
(
)
)
;
if
(
targetHostAttrVal
==
||
targetHostAttrVal
.
isEmpty
(
)
)
{
return
new
Result
(
false
,
hostAttributeName
+
" attribute unavailable on host "
+
targetVM
.
getCurrAvailableResources
(
)
.
hostname
(
)
)
;
}
String
requiredAttrVal
=
hostAttributeValueGetter
.
call
(
taskRequest
.
getId
(
)
)
;
return
targetHostAttrVal
.
equals
(
requiredAttrVal
)
new
Result
(
true
,
""
)
:
new
Result
(
false
,
"Host attribute "
+
hostAttributeName
+
": required="
+
requiredAttrVal
+
", got="
+
targetHostAttrVal
)
;
}

Tests a host to determine whether it has an attribute of the required value for this task request.

@param taskRequest      describes the task being evaluated for assignment to the host
@param targetVM         describes the host being evaluated as a target for the task
@param taskTrackerState describes the state of tasks already assigned or running on hosts throughout the
system
@return a successful Result if the host has an attribute with the required value, or an unsuccessful
Result otherwise

Tests a host to determine whether it has an attribute of the required value for this task request .


@Override
    public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
        Set<String> coTasks = coTasksGetter.call(taskRequest.getId());
        String targetHostAttrVal = AttributeUtilities.getAttrValue(targetVM.getCurrAvailableResources(), hostAttributeName);
        if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) {
            return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname());
        }
        for(String coTask: coTasks) {
            TaskTracker.ActiveTask activeTask = taskTrackerState.getAllRunningTasks().get(coTask);
            if(activeTask==null)
                activeTask = taskTrackerState.getAllCurrentlyAssignedTasks().get(coTask);
            if(activeTask!=null) {
                String usedAttrVal = AttributeUtilities.getAttrValue(activeTask.getTotalLease(), hostAttributeName);
                if(usedAttrVal==null || usedAttrVal.isEmpty())
                    return new Result(false, hostAttributeName+" attribute unavailable on host " + activeTask.getTotalLease().hostname() +
                            " running co-task " + coTask);
                if(usedAttrVal.equals(targetHostAttrVal)) {
                    return new Result(false, hostAttributeName+" " + targetHostAttrVal + " already used for another co-task " + coTask);
                }
            }
        }
        return new Result(true, "");
    }

@
Override
public
Result
evaluate
(
TaskRequest
taskRequest
,
VirtualMachineCurrentState
targetVM
,
TaskTrackerState
taskTrackerState
)
{
Set
<
String
>
coTasks
=
coTasksGetter
.
call
(
taskRequest
.
getId
(
)
)
;
String
targetHostAttrVal
=
AttributeUtilities
.
getAttrValue
(
targetVM
.
getCurrAvailableResources
(
)
,
hostAttributeName
)
;
if
(
targetHostAttrVal
==
||
targetHostAttrVal
.
isEmpty
(
)
)
{
return
new
Result
(
false
,
hostAttributeName
+
" attribute unavailable on host "
+
targetVM
.
getCurrAvailableResources
(
)
.
hostname
(
)
)
;
}
for
(
String
coTask
:
coTasks
)
{
TaskTracker
.
ActiveTask
activeTask
=
taskTrackerState
.
getAllRunningTasks
(
)
.
get
(
coTask
)
;
if
(
activeTask
==
)
activeTask
=
taskTrackerState
.
getAllCurrentlyAssignedTasks
(
)
.
get
(
coTask
)
;
if
(
activeTask
!=
)
{
String
usedAttrVal
=
AttributeUtilities
.
getAttrValue
(
activeTask
.
getTotalLease
(
)
,
hostAttributeName
)
;
if
(
usedAttrVal
==
||
usedAttrVal
.
isEmpty
(
)
)
return
new
Result
(
false
,
hostAttributeName
+
" attribute unavailable on host "
+
activeTask
.
getTotalLease
(
)
.
hostname
(
)
+
" running co-task "
+
coTask
)
;
if
(
usedAttrVal
.
equals
(
targetHostAttrVal
)
)
{
return
new
Result
(
false
,
hostAttributeName
+
" "
+
targetHostAttrVal
+
" already used for another co-task "
+
coTask
)
;
}
}
}
return
new
Result
(
true
,
""
)
;
}

Determines whether a particular target host is appropriate for a particular task request by rejecting any
host that has the same value for the unique constraint attribute as another host that is already assigned
a co-task of the specified task request.

@param taskRequest      describes the task being considered for assignment to the host
@param targetVM         describes the host being considered as a target for the task
@param taskTrackerState describes the state of tasks previously assigned or already running throughout
the system
@return a successful Result if the target does not have the same value for its unique constraint
attribute as another host that has already been assigned a co-task of {@code taskRequest}, or an
unsuccessful Result otherwise

Determines whether a particular target host is appropriate for a particular task request by rejecting any host that has the same value for the unique constraint attribute as another host that is already assigned a co - task of the specified task request .


public void setAutoscalerCallback(Action1<AutoScaleAction> callback) throws IllegalStateException {
        checkIfShutdown();
        if (autoScaler == null) {
            throw new IllegalStateException("No autoScaler setup");
        }
        autoScaler.setCallback(callback);
    }

public
void
setAutoscalerCallback
(
Action1
<
AutoScaleAction
>
callback
)
throws
IllegalStateException
{
checkIfShutdown
(
)
;
if
(
autoScaler
==
)
{
throw
new
IllegalStateException
(
"No autoScaler setup"
)
;
}
autoScaler
.
setCallback
(
callback
)
;
}

Set the autoscale call back action. The callback you pass to this method receives an indication when an
autoscale action is to be performed, telling it which autoscale rule prompted the action and whether the
action is to scale up or scale down the autoscale group. The callback then initiates the appropriate
scaling actions.

@param callback the callback to invoke for autoscale actions
@throws IllegalStateException if no autoscaler was established
@see Autoscaling

Set the autoscale call back action . The callback you pass to this method receives an indication when an autoscale action is to be performed telling it which autoscale rule prompted the action and whether the action is to scale up or scale down the autoscale group . The callback then initiates the appropriate scaling actions .


public void disableVM(String hostname, long durationMillis) throws IllegalStateException {
        logger.debug("Disable VM " + hostname + " for " + durationMillis + " millis");
        assignableVMs.disableUntil(hostname, System.currentTimeMillis() + durationMillis);
    }

public
void
disableVM
(
String
hostname
,
long
durationMillis
)
throws
IllegalStateException
{
logger
.
debug
(
"Disable VM "
+
hostname
+
" for "
+
durationMillis
+
" millis"
)
;
assignableVMs
.
disableUntil
(
hostname
,
System
.
currentTimeMillis
(
)
+
durationMillis
)
;
}

Disable the virtual machine with the specified hostname. The scheduler will not use disabled hosts for
allocating resources to tasks.

@param hostname       the name of the host to disable
@param durationMillis the length of time, starting from now, in milliseconds, during which the host will
be disabled
@throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.

Disable the virtual machine with the specified hostname . The scheduler will not use disabled hosts for allocating resources to tasks .


public boolean disableVMByVMId(String vmID, long durationMillis) throws IllegalStateException {
        final String hostname = assignableVMs.getHostnameFromVMId(vmID);
        if (hostname == null) {
            return false;
        }
        disableVM(hostname, durationMillis);
        return true;
    }

public boolean disableVMByVMId ( String vmID , long durationMillis ) throws IllegalStateException { final String hostname = assignableVMs . getHostnameFromVMId ( vmID ) ; if ( hostname == null ) { return false ; } disableVM ( hostname , durationMillis ) ; return true ; }

Disable the virtual machine with the specified ID. The scheduler will not use disabled hosts for allocating
resources to tasks.

@param vmID           the ID of the host to disable
@param durationMillis the length of time, starting from now, in milliseconds, during which the host will
be disabled
@return {@code true} if the ID matches a known VM, {@code false} otherwise.
@throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.

Disable the virtual machine with the specified ID . The scheduler will not use disabled hosts for allocating resources to tasks .


public void enableVM(String hostname) throws IllegalStateException {
        logger.debug("Enabling VM " + hostname);
        assignableVMs.enableVM(hostname);
    }

public
void
enableVM
(
String
hostname
)
throws
IllegalStateException
{
logger
.
debug
(
"Enabling VM "
+
hostname
)
;
assignableVMs
.
enableVM
(
hostname
)
;
}

Enable the VM with the specified host name. Hosts start in an enabled state, so you only need to call
this method if you have previously explicitly disabled the host.

@param hostname the name of the host to enable
@throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.

Enable the VM with the specified host name . Hosts start in an enabled state so you only need to call this method if you have previously explicitly disabled the host .


public void shutdown() {
        if (isShutdown.compareAndSet(false, true)) {
            executorService.shutdown();
            if (autoScaler != null) {
                autoScaler.shutdown();
            }
        }
    }

public void shutdown ( ) { if ( isShutdown . compareAndSet ( false , true ) ) { executorService . shutdown ( ) ; if ( autoScaler != null ) { autoScaler . shutdown ( ) ; } } }

Mark task scheduler as shutdown and shutdown any thread pool executors created.

Mark task scheduler as shutdown and shutdown any thread pool executors created .


public boolean hasProperties(String... properties) {
        for (String property : properties) {
            if (!hasProperty(property)) {
                return false;
            }
        }
        return true;
    }

public boolean hasProperties ( String ... properties ) { for ( String property : properties ) { if ( ! hasProperty ( property ) ) { return false ; } } return true ; }

Check if this entity contains all of the given properties.

@param properties Names of the properties
@return True, if and only if the given properties are present in this entity

Check if this entity contains all of the given properties .


public static Demo.CDemoFileInfo infoForSource(final Source source) throws IOException {
        EngineType engineType = source.readEngineType();
        source.setPosition(source.readFixedInt32());
        PacketInstance<GeneratedMessage> pi = engineType.getNextPacketInstance(source);
        return (Demo.CDemoFileInfo) pi.parse();
    }

public static Demo . CDemoFileInfo infoForSource ( final Source source ) throws IOException { EngineType engineType = source . readEngineType ( ) ; source . setPosition ( source . readFixedInt32 ( ) ) ; PacketInstance < GeneratedMessage > pi = engineType . getNextPacketInstance ( source ) ; return ( Demo . CDemoFileInfo ) pi . parse ( ) ; }

Retrieves summary-data from the given input source

@param source the {@code Source} providing the replay data
@return the {@code CDemoFileInfo} protobuf message
@throws IOException if the given source is invalid
@see Source

Retrieves summary - data from the given input source


private static S2DotaMatchMetadata.CDOTAMatchMetadataFile metadataForStream(InputStream stream) throws IOException {
        return Packet.parse(S2DotaMatchMetadata.CDOTAMatchMetadataFile.class, ByteString.readFrom(stream));
    }

private static S2DotaMatchMetadata . CDOTAMatchMetadataFile metadataForStream ( InputStream stream ) throws IOException { return Packet . parse ( S2DotaMatchMetadata . CDOTAMatchMetadataFile . class , ByteString . readFrom ( stream ) ) ; }

reads a metadata stream and returns it's contents

@param stream an {@code InputStream}, containing replay data, positioned at the beginning
@return the {@code CDOTAMatchMetadataFile} protobuf message
@throws IOException if the given stream is invalid

reads a metadata stream and returns it s contents


private byte[] readPacket(Source source) throws IOException {
        int size = source.readFixedInt32();
        return packetReader.readFromSource(source, size, false);
    }

private byte [ ] readPacket ( Source source ) throws IOException { int size = source . readFixedInt32 ( ) ; return packetReader . readFromSource ( source , size , false ) ; }


public int readVarInt32() throws IOException {
        byte tmp = readByte();
        if (tmp >= 0) {
            return tmp;
        }
        int result = tmp & 0x7f;
        if ((tmp = readByte()) >= 0) {
            result |= tmp << 7;
        } else {
            result |= (tmp & 0x7f) << 7;
            if ((tmp = readByte()) >= 0) {
                result |= tmp << 14;
            } else {
                result |= (tmp & 0x7f) << 14;
                if ((tmp = readByte()) >= 0) {
                    result |= tmp << 21;
                } else {
                    result |= (tmp & 0x7f) << 21;
                    result |= (tmp = readByte()) << 28;
                    if (tmp < 0) {
                        throw new IOException("malformed varint detected");
                    }
                }
            }
        }
        return result;
    }

public
int
readVarInt32
(
)
throws
IOException
{
byte
tmp
=
readByte
(
)
;
if
(
tmp
>=
0
)
{
return
tmp
;
}
int
result
=
tmp
&
0x7f
;
if
(
(
tmp
=
readByte
(
)
)
>=
0
)
{
result
|=
tmp
<<
7
;
}
else
{
result
|=
(
tmp
&
0x7f
)
<<
7
;
if
(
(
tmp
=
readByte
(
)
)
>=
0
)
{
result
|=
tmp
<<
14
;
}
else
{
result
|=
(
tmp
&
0x7f
)
<<
14
;
if
(
(
tmp
=
readByte
(
)
)
>=
0
)
{
result
|=
tmp
<<
21
;
}
else
{
result
|=
(
tmp
&
0x7f
)
<<
21
;
result
|=
(
tmp
=
readByte
(
)
)
<<
28
;
if
(
tmp
<
0
)
{
throw
new
IOException
(
"malformed varint detected"
)
;
}
}
}
}
return
result
;
}

reads a variable int32 from the current position

@return the int
@throws IOException if the data cannot be read, or is not a valid variable int32


public int readFixedInt32() throws IOException {
        return ByteBuffer.wrap(readBytes(4)).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();
    }

public int readFixedInt32 ( ) throws IOException { return ByteBuffer . wrap ( readBytes ( 4 ) ) . order ( ByteOrder . LITTLE_ENDIAN ) . asIntBuffer ( ) . get ( ) ; }

reads a fixed int32 from the current position

@return the int
@throws IOException if the data cannot be read


public EngineType readEngineType() throws IOException {
        try {
            engineType = EngineId.typeForMagic(new String(readBytes(8)));
            if (engineType == null) {
                throw new IOException();
            }
            return engineType;
        } catch (IOException e) {
            throw new IOException("given stream does not seem to contain a valid replay");
        }
    }

reads the magic of a demo file, identifying the engine type

@throws IOException if there is not enough data or the if no valid magic was found

reads the magic of a demo file identifying the engine type


public ContainerTag with(DomContent child) {
        if (this == child) {
            throw new RuntimeException("Cannot append a tag to itself.");
        }
        if (child == null) {
            return this; // in some cases, like when using iff(), we ignore null children
        }
        children.add(child);
        return this;
    }

Appends a DomContent-object to the end of this element

@param child DomContent-object to be appended
@return itself for easy chaining

Appends a DomContent - object to the end of this element


public ContainerTag with(Iterable<? extends DomContent> children) {
        if (children != null) {
            for (DomContent child : children) {
                this.with(child);
            }
        }
        return this;
    }

public ContainerTag with ( Iterable < ? extends DomContent > children ) { if ( children != null ) { for ( DomContent child : children ) { this . with ( child ) ; } } return this ; }

Appends a list of DomContent-objects to the end of this element

@param children DomContent-objects to be appended
@return itself for easy chaining

Appends a list of DomContent - objects to the end of this element


@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
    public static <T, U> T iff(Optional<U> optional, Function<U, T> ifFunction) {
        if (Objects.nonNull(optional) && optional.isPresent()) {
            return optional.map(ifFunction).orElse(null);
        }
        return null;
    }

@ SuppressWarnings ( "OptionalUsedAsFieldOrParameterType" ) public static < T , U > T iff ( Optional < U > optional , Function < U , T > ifFunction ) { if ( Objects . nonNull ( optional ) && optional . isPresent ( ) ) { return optional . map ( ifFunction ) . orElse ( null ) ; } return null ; }

Generic if-expression to if'ing inside method calls

@param optional   The item that may be present
@param ifFunction The function that will be called if that optional is present
@param <T>        The derived generic parameter type
@param <U>        The supplying generic parameter type
@return transformed value if condition is true, null otherwise

Generic if - expression to if ing inside method calls


public static String document(ContainerTag htmlTag) {
        if (htmlTag.getTagName().equals("html")) {
            return document().render() + htmlTag.render();
        }
        throw new IllegalArgumentException("Only HTML-tag can follow document declaration");
    }

Return a complete html document string

@param htmlTag the html content of a website
@return document declaration and rendered html content


boolean setAttribute(String name, String value) {
        if (value == null) {
            return attributes.add(new Attribute(name));
        }
        for (Attribute attribute : attributes) {
            if (attribute.getName().equals(name)) {
                attribute.setValue(value); // update with new value
                return true;
            }
        }
        return attributes.add(new Attribute(name, value));
    }

boolean
setAttribute
(
String
name
,
String
value
)
{
if
(
value
==
)
{
return
attributes
.
add
(
new
Attribute
(
name
)
)
;
}
for
(
Attribute
attribute
:
attributes
)
{
if
(
attribute
.
getName
(
)
.
equals
(
name
)
)
{
attribute
.
setValue
(
value
)
;
// update with new value
return
true
;
}
}
return
attributes
.
add
(
new
Attribute
(
name
,
value
)
)
;
}

Sets an attribute on an element

@param name  the attribute
@param value the attribute value


public T attr(String attribute, Object value) {
        setAttribute(attribute, value == null ? null : String.valueOf(value));
        return (T) this;
    }

public T attr ( String attribute , Object value ) { setAttribute ( attribute , value == null ? null : String . valueOf ( value ) ) ; return ( T ) this ; }

Sets a custom attribute

@param attribute the attribute name
@param value     the attribute value
@return itself for easy chaining


public T attr(Attribute attribute) {
        Iterator<Attribute> iterator = attributes.iterator();
        String name = attribute.getName();
        if (name != null) {
            // name == null is allowed, but those Attributes are not rendered. So we add them anyway.
            while (iterator.hasNext()) {
                Attribute existingAttribute = iterator.next();
                if (existingAttribute.getName().equals(name)) {
                    iterator.remove();
                }
            }
        }
        attributes.add(attribute);
        return (T) this;
    }

Adds the specified attribute. If the Tag previously contained an attribute with the same name, the old attribute is replaced by the specified attribute.

@param attribute the attribute
@return itself for easy chaining

Adds the specified attribute . If the Tag previously contained an attribute with the same name the old attribute is replaced by the specified attribute .


public T withClasses(String... classes) {
        StringBuilder sb = new StringBuilder();
        for (String s : classes) {
            sb.append(s != null ? s : "").append(" ");
        }
        return attr(Attr.CLASS, sb.toString().trim());
    }

public
T
withClasses
(
String
...
classes
)
{
StringBuilder
sb
=
new
StringBuilder
(
)
;
for
(
String
s
:
classes
)
{
sb
.
append
(
s
!=
s
:
""
)
.
append
(
" "
)
;
}
return
attr
(
Attr
.
CLASS
,
sb
.
toString
(
)
.
trim
(
)
)
;
}

Convenience methods that call attr with predefined attributes

@return itself for easy chaining


public static String compressJs(String code) {
        InputStream inStream = new ByteArrayInputStream(code.getBytes());
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        JSMin jsmin = new JSMin(inStream, outStream);
        try {
            jsmin.jsmin();
            return outStream.toString().trim();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

public static String compressJs ( String code ) { InputStream inStream = new ByteArrayInputStream ( code . getBytes ( ) ) ; ByteArrayOutputStream outStream = new ByteArrayOutputStream ( ) ; JSMin jsmin = new JSMin ( inStream , outStream ) ; try { jsmin . jsmin ( ) ; return outStream . toString ( ) . trim ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return "" ; } }

Compress a JS-string

@param code the js-code you want to compress
@return the compressed code


private ArrayList<Property> parseProperties(String contents) {
        ArrayList<String> parts = new ArrayList<>();
        boolean bInsideString = false,
            bInsideURL = false;
        int j = 0;
        String substr;
        for (int i = 0; i < contents.length(); i++) {
            if (bInsideString) { // If we're inside a string
                bInsideString = !(contents.charAt(i) == '"');
            } else if (bInsideURL) { // If we're inside a URL
                bInsideURL = !(contents.charAt(i) == ')');
            } else if (contents.charAt(i) == '"') {
                bInsideString = true;
            } else if (contents.charAt(i) == '(') {
                if ((i - 3) > 0 && "url".equals(contents.substring(i - 3, i))) {
                    bInsideURL = true;
                }
            } else if (contents.charAt(i) == ';') {
                substr = contents.substring(j, i);
                if (!(substr.trim().equals(""))) {
                    parts.add(substr);
                }
                j = i + 1;
            }
        }
        substr = contents.substring(j, contents.length());
        if (!(substr.trim().equals(""))) {
            parts.add(substr);
        }

        ArrayList<Property> results = new ArrayList<>();
        for (String part : parts) {
            try {
                results.add(new Property(part));
            } catch (IncompletePropertyException ipex) {
                LOG.warning("Incomplete property in selector \"" + this.selector + "\": \"" + ipex.getMessage() + "\"");
            }
        }

        return results;
    }

private
ArrayList
<
Property
>
parseProperties
(
String
contents
)
{
ArrayList
<
String
>
parts
=
new
ArrayList
<>
(
)
;
boolean
bInsideString
=
false
,
bInsideURL
=
false
;
int
j
=
0
;
String
substr
;
for
(
int
i
=
0
;
i
<
contents
.
length
(
)
;
i
++
)
{
if
(
bInsideString
)
{
// If we're inside a string
bInsideString
=
!
(
contents
.
charAt
(
i
)
==
'
'
)
;
}
else
if
(
bInsideURL
)
{
// If we're inside a URL
bInsideURL
=
!
(
contents
.
charAt
(
i
)
==
'
'
)
;
}
else
if
(
contents
.
charAt
(
i
)
==
'
'
)
{
bInsideString
=
true
;
}
else
if
(
contents
.
charAt
(
i
)
==
'
'
)
{
if
(
(
i
3
)
>
0
&&
"url"
.
equals
(
contents
.
substring
(
i
3
,
i
)
)
)
{
bInsideURL
=
true
;
}
}
else
if
(
contents
.
charAt
(
i
)
==
'
'
)
{
substr
=
contents
.
substring
(
j
,
i
)
;
if
(
!
(
substr
.
trim
(
)
.
equals
(
""
)
)
)
{
parts
.
add
(
substr
)
;
}
j
=
i
+
1
;
}
}
substr
=
contents
.
substring
(
j
,
contents
.
length
(
)
)
;
if
(
!
(
substr
.
trim
(
)
.
equals
(
""
)
)
)
{
parts
.
add
(
substr
)
;
}
ArrayList
<
Property
>
results
=
new
ArrayList
<>
(
)
;
for
(
String
part
:
parts
)
{
try
{
results
.
add
(
new
Property
(
part
)
)
;
}
catch
(
IncompletePropertyException
ipex
)
{
LOG
.
warning
(
"Incomplete property in selector \""
+
this
.
selector
+
"\": \""
+
ipex
.
getMessage
(
)
+
"\""
)
;
}
}
return
results
;
}

Parses out the properties of a selector's body.

@param contents The body; for example, "border: solid 1px red; color: blue;"
@return An array of properties parsed from this selector.

Parses out the properties of a selector s body .


private Part[] parseValues(String contents) {
        String[] parts = contents.split(",");
        Part[] results = new Part[parts.length];

        for (int i = 0; i < parts.length; i++) {
            try {
                results[i] = new Part(parts[i], property);
            } catch (Exception e) {
                LOG.warning(e.getMessage());
                results[i] = null;
            }
        }

        return results;
    }

private Part [ ] parseValues ( String contents ) { String [ ] parts = contents . split ( "," ) ; Part [ ] results = new Part [ parts . length ] ; for ( int i = 0 ; i < parts . length ; i ++ ) { try { results [ i ] = new Part ( parts [ i ] , property ) ; } catch ( Exception e ) { LOG . warning ( e . getMessage ( ) ) ; results [ i ] = null ; } } return results ; }

Parse the values out of a property.

@param contents The property to parse
@return An array of Parts


private void handleOnVisibleMenuItemsWidthChanged(int menuItemsWidth) {
        if (menuItemsWidth == 0) {
            mClearButton.setTranslationX(-Util.dpToPx(4));
            int paddingRight = Util.dpToPx(4);
            if (mIsFocused) {
                paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH_DP);
            } else {
                paddingRight += Util.dpToPx(14);
            }
            mSearchInput.setPadding(0, 0, paddingRight, 0);
        } else {
            mClearButton.setTranslationX(-menuItemsWidth);
            int paddingRight = menuItemsWidth;
            if (mIsFocused) {
                paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH_DP);
            }
            mSearchInput.setPadding(0, 0, paddingRight, 0);
        }
    }

private void handleOnVisibleMenuItemsWidthChanged ( int menuItemsWidth ) { if ( menuItemsWidth == 0 ) { mClearButton . setTranslationX ( - Util . dpToPx ( 4 ) ) ; int paddingRight = Util . dpToPx ( 4 ) ; if ( mIsFocused ) { paddingRight += Util . dpToPx ( CLEAR_BTN_WIDTH_DP ) ; } else { paddingRight += Util . dpToPx ( 14 ) ; } mSearchInput . setPadding ( 0 , 0 , paddingRight , 0 ) ; } else { mClearButton . setTranslationX ( - menuItemsWidth ) ; int paddingRight = menuItemsWidth ; if ( mIsFocused ) { paddingRight += Util . dpToPx ( CLEAR_BTN_WIDTH_DP ) ; } mSearchInput . setPadding ( 0 , 0 , paddingRight , 0 ) ; } }

ensures that the end margin of the search input is according to Material specs


public void setLeftActionIconColor(int color) {
        mLeftActionIconColor = color;
        mMenuBtnDrawable.setColor(color);
        DrawableCompat.setTint(mIconBackArrow, color);
        DrawableCompat.setTint(mIconSearch, color);
    }

public void setLeftActionIconColor ( int color ) { mLeftActionIconColor = color ; mMenuBtnDrawable . setColor ( color ) ; DrawableCompat . setTint ( mIconBackArrow , color ) ; DrawableCompat . setTint ( mIconSearch , color ) ; }

Sets the menu button's color.

@param color the color to be applied to the
left menu button.


public void setBackgroundColor(int color) {
        mBackgroundColor = color;
        if (mQuerySection != null && mSuggestionsList != null) {
            mQuerySection.setCardBackgroundColor(color);
            mSuggestionsList.setBackgroundColor(color);
        }
    }

public void setBackgroundColor ( int color ) { mBackgroundColor = color ; if ( mQuerySection != null && mSuggestionsList != null ) { mQuerySection . setCardBackgroundColor ( color ) ; mSuggestionsList . setBackgroundColor ( color ) ; } }

Sets the background color of the search
view including the suggestions section.

@param color the color to be applied to the search bar and
the suggestion section background.

Sets the background color of the search view including the suggestions section .


public void openMenu(boolean withAnim) {
        mMenuOpen = true;
        openMenuDrawable(mMenuBtnDrawable, withAnim);
        if (mOnMenuClickListener != null) {
            mOnMenuClickListener.onMenuOpened();
        }
    }

public void openMenu ( boolean withAnim ) { mMenuOpen = true ; openMenuDrawable ( mMenuBtnDrawable , withAnim ) ; if ( mOnMenuClickListener != null ) { mOnMenuClickListener . onMenuOpened ( ) ; } }

Mimics a menu click that opens the menu. Useful for navigation
drawers when they open as a result of dragging.

Mimics a menu click that opens the menu . Useful for navigation drawers when they open as a result of dragging .


public void closeMenu(boolean withAnim) {
        mMenuOpen = false;
        closeMenuDrawable(mMenuBtnDrawable, withAnim);
        if (mOnMenuClickListener != null) {
            mOnMenuClickListener.onMenuClosed();
        }
    }

public void closeMenu ( boolean withAnim ) { mMenuOpen = false ; closeMenuDrawable ( mMenuBtnDrawable , withAnim ) ; if ( mOnMenuClickListener != null ) { mOnMenuClickListener . onMenuClosed ( ) ; } }

Mimics a menu click that closes. Useful when fo navigation
drawers when they close as a result of selecting and item.

@param withAnim true, will close the menu button with
the  Material animation

Mimics a menu click that closes . Useful when fo navigation drawers when they close as a result of selecting and item .


public void inflateOverflowMenu(int menuId) {
        mMenuId = menuId;
        mMenuView.reset(menuId, actionMenuAvailWidth());
        if (mIsFocused) {
            mMenuView.hideIfRoomItems(false);
        }
    }

public void inflateOverflowMenu ( int menuId ) { mMenuId = menuId ; mMenuView . reset ( menuId , actionMenuAvailWidth ( ) ) ; if ( mIsFocused ) { mMenuView . hideIfRoomItems ( false ) ; } }

Inflates the menu items from
an xml resource.

@param menuId a menu xml resource reference

Inflates the menu items from an xml resource .


public void setShowSearchKey(boolean show) {
        mShowSearchKey = show;
        if (show) {
            mSearchInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        } else {
            mSearchInput.setImeOptions(EditorInfo.IME_ACTION_NONE);
        }
    }

public void setShowSearchKey ( boolean show ) { mShowSearchKey = show ; if ( show ) { mSearchInput . setImeOptions ( EditorInfo . IME_ACTION_SEARCH ) ; } else { mSearchInput . setImeOptions ( EditorInfo . IME_ACTION_NONE ) ; } }

Sets whether the the button with the search icon
will appear in the soft-keyboard or not.

@param show to show the search button in
the soft-keyboard.

Sets whether the the button with the search icon will appear in the soft - keyboard or not .


public void setDismissOnOutsideClick(boolean enable) {

        mDismissOnOutsideTouch = enable;
        mSuggestionsSection.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                //todo check if this is called twice
                if (mDismissOnOutsideTouch && mIsFocused) {
                    setSearchFocusedInternal(false);
                }

                return true;
            }
        });
    }

public
void
setDismissOnOutsideClick
(
boolean
enable
)
{
mDismissOnOutsideTouch
=
enable
;
mSuggestionsSection
.
setOnTouchListener
(
new
OnTouchListener
(
)
{
@
Override
public
boolean
onTouch
(
View
v
,
MotionEvent
event
)
{
//todo check if this is called twice
if
(
mDismissOnOutsideTouch
&&
mIsFocused
)
{
setSearchFocusedInternal
(
false
)
;
}
return
true
;
}
}
)
;
}

Set whether a touch outside of the
search bar's bounds will cause the search bar to
loos focus.

@param enable true to dismiss on outside touch, false otherwise.

Set whether a touch outside of the search bar s bounds will cause the search bar to loos focus .


public boolean setSearchFocused(final boolean focused) {

        boolean updatedToNotFocused = !focused && this.mIsFocused;

        if ((focused != this.mIsFocused) && mSuggestionSecHeightListener == null) {
            if (mIsSuggestionsSectionHeightSet) {
                setSearchFocusedInternal(focused);
            } else {
                mSuggestionSecHeightListener = new OnSuggestionSecHeightSetListener() {
                    @Override
                    public void onSuggestionSecHeightSet() {
                        setSearchFocusedInternal(focused);
                        mSuggestionSecHeightListener = null;
                    }
                };
            }
        }
        return updatedToNotFocused;
    }

public boolean setSearchFocused ( final boolean focused ) { boolean updatedToNotFocused = ! focused && this . mIsFocused ; if ( ( focused != this . mIsFocused ) && mSuggestionSecHeightListener == null ) { if ( mIsSuggestionsSectionHeightSet ) { setSearchFocusedInternal ( focused ) ; } else { mSuggestionSecHeightListener = new OnSuggestionSecHeightSetListener ( ) { @ Override public void onSuggestionSecHeightSet ( ) { setSearchFocusedInternal ( focused ) ; mSuggestionSecHeightListener = null ; } } ; } } return updatedToNotFocused ; }

Sets whether the search is focused or not.

@param focused true, to set the search to be active/focused.
@return true if the search was focused and will now become not focused. Useful for
calling supper.onBackPress() in the hosting activity only if this method returns false

Sets whether the search is focused or not .


private boolean updateSuggestionsSectionHeight(List<? extends SearchSuggestion>
                                                           newSearchSuggestions, boolean withAnim) {

        final int cardTopBottomShadowPadding = Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT);
        final int cardRadiusSize = Util.dpToPx(CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT);

        int visibleSuggestionHeight = calculateSuggestionItemsHeight(newSearchSuggestions,
                mSuggestionListContainer.getHeight());
        int diff = mSuggestionListContainer.getHeight() - visibleSuggestionHeight;
        int addedTranslationYForShadowOffsets = (diff <= cardTopBottomShadowPadding) ?
                -(cardTopBottomShadowPadding - diff) :
                diff < (mSuggestionListContainer.getHeight() - cardTopBottomShadowPadding) ? cardRadiusSize : 0;
        final float newTranslationY = -mSuggestionListContainer.getHeight() +
                visibleSuggestionHeight + addedTranslationYForShadowOffsets;

        //todo go over
        final float fullyInvisibleTranslationY = -mSuggestionListContainer.getHeight() + cardRadiusSize;

        ViewCompat.animate(mSuggestionListContainer).cancel();
        if (withAnim) {
            ViewCompat.animate(mSuggestionListContainer).
                    setInterpolator(SUGGEST_ITEM_ADD_ANIM_INTERPOLATOR).
                    setDuration(mSuggestionSectionAnimDuration).
                    translationY(newTranslationY)
                    .setUpdateListener(new ViewPropertyAnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(View view) {

                            if (mOnSuggestionsListHeightChanged != null) {
                                float newSuggestionsHeight = Math.abs(view.getTranslationY() - fullyInvisibleTranslationY);
                                mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight);
                            }
                        }
                    })
                    .setListener(new ViewPropertyAnimatorListenerAdapter() {
                        @Override
                        public void onAnimationCancel(View view) {
                            mSuggestionListContainer.setTranslationY(newTranslationY);
                        }
                    }).start();
        } else {
            mSuggestionListContainer.setTranslationY(newTranslationY);
            if (mOnSuggestionsListHeightChanged != null) {
                float newSuggestionsHeight = Math.abs(mSuggestionListContainer.getTranslationY() - fullyInvisibleTranslationY);
                mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight);
            }
        }

        return mSuggestionListContainer.getHeight() == visibleSuggestionHeight;
    }

returns true if the suggestion items occupy the full RecyclerView's height, false otherwise

returns true if the suggestion items occupy the full RecyclerView s height false otherwise


private int calculateSuggestionItemsHeight(List<? extends SearchSuggestion> suggestions, int max) {

        //todo
        // 'i < suggestions.size()' in the below 'for' seems unneeded, investigate if there is a use for it.
        int visibleItemsHeight = 0;
        for (int i = 0; i < suggestions.size() && i < mSuggestionsList.getChildCount(); i++) {
            visibleItemsHeight += mSuggestionsList.getChildAt(i).getHeight();
            if (visibleItemsHeight > max) {
                visibleItemsHeight = max;
                break;
            }
        }
        return visibleItemsHeight;
    }

results is >= max. The max option allows us to avoid doing unnecessary and potentially long calculations.

results is > = max . The max option allows us to avoid doing unnecessary and potentially long calculations .


public void setOnBindSuggestionCallback(SearchSuggestionsAdapter.OnBindSuggestionCallback callback) {
        this.mOnBindSuggestionCallback = callback;
        if (mSuggestionsAdapter != null) {
            mSuggestionsAdapter.setOnBindSuggestionCallback(mOnBindSuggestionCallback);
        }
    }

public void setOnBindSuggestionCallback ( SearchSuggestionsAdapter . OnBindSuggestionCallback callback ) { this . mOnBindSuggestionCallback = callback ; if ( mSuggestionsAdapter != null ) { mSuggestionsAdapter . setOnBindSuggestionCallback ( mOnBindSuggestionCallback ) ; } }

Set a callback that will be called after each suggestion view in the suggestions recycler
list is bound. This allows for customized binding for specific items in the list.

@param callback A callback to be called after a suggestion is bound by the suggestions list's
adapter.

Set a callback that will be called after each suggestion view in the suggestions recycler list is bound . This allows for customized binding for specific items in the list .


public static String getMD5Checksum(String filename) {
       try {
           byte[] b = createChecksum(filename);
           String result = "";

           for (int i=0; i < b.length; i++) {
               result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
           }
           return result;
       } catch (Exception e){
           return "";
       }
   }

public static String getMD5Checksum ( String filename ) { try { byte [ ] b = createChecksum ( filename ) ; String result = "" ; for ( int i = 0 ; i < b . length ; i ++ ) { result += Integer . toString ( ( b [ i ] & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ; } return result ; } catch ( Exception e ) { return "" ; } }


public static OkHttpClient.Builder configureToIgnoreCertificate(OkHttpClient.Builder builder) {
        log.warn("Ignore Ssl Certificate");
        try {
            /*Create a trust manager that does not validate certificate chains*/
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            /*Install the all-trusting trust manager*/
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            /*Create an ssl socket factory with our all-trusting manager*/
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception e) {
            log.warn("Exception while configuring IgnoreSslCertificate" + e, e);
        }
        return builder;
    }

Setting testMode configuration. If set as testMode, the connection will skip certification check

@param builder
@return

Setting testMode configuration . If set as testMode the connection will skip certification check


@SuppressWarnings("unchecked")
  @Override
  public T read(JsonReader in) throws IOException {
    List<Exception> exceptions = new ArrayList<>(subtypes.length);
    ReaderSupplier readerSupplier = readForSupplier(in);
    for (TypeAdapter<?> typeAdapter : adapters) {
      try {
        return (T) typeAdapter.read(readerSupplier.create());
      } catch (Exception ex) {
        exceptions.add(ex);
      }
    }
    JsonParseException failure = new JsonParseException(
        String.format(
            "Cannot parse %s with following subtypes: %s",
            type,
            Arrays.toString(subtypes)));
    for (Exception exception : exceptions) {
      failure.addSuppressed(exception);
    }
    throw failure;
  }


@Value.Lazy
  public NameForms typeAbstract() {
    if (protoclass().kind().isConstructor()) {
      return typeValue();
    }

    List<String> classSegments = Lists.newArrayListWithExpectedSize(2);
    Element e = SourceNames.collectClassSegments(protoclass().sourceElement(), classSegments);
    verify(e instanceof PackageElement);

    String packageOf = ((PackageElement) e).getQualifiedName().toString();
    String relative = DOT_JOINER.join(classSegments);
    boolean relativeAlreadyQualified = false;

    if (!implementationPackage().equals(packageOf)) {
      relative = DOT_JOINER.join(packageOf, relative);
      relativeAlreadyQualified = true;
    }

    return ImmutableConstitution.NameForms.builder()
        .simple(names().typeAbstract)
        .relativeRaw(relative)
        .packageOf(packageOf)
        .genericArgs(generics().args())
        .relativeAlreadyQualified(relativeAlreadyQualified)
        .visibility(protoclass().visibility())
        .build();
  }

@ Value . Lazy public NameForms typeAbstract ( ) { if ( protoclass ( ) . kind ( ) . isConstructor ( ) ) { return typeValue ( ) ; } List < String > classSegments = Lists . newArrayListWithExpectedSize ( 2 ) ; Element e = SourceNames . collectClassSegments ( protoclass ( ) . sourceElement ( ) , classSegments ) ; verify ( e instanceof PackageElement ) ; String packageOf = ( ( PackageElement ) e ) . getQualifiedName ( ) . toString ( ) ; String relative = DOT_JOINER . join ( classSegments ) ; boolean relativeAlreadyQualified = false ; if ( ! implementationPackage ( ) . equals ( packageOf ) ) { relative = DOT_JOINER . join ( packageOf , relative ) ; relativeAlreadyQualified = true ; } return ImmutableConstitution . NameForms . builder ( ) . simple ( names ( ) . typeAbstract ) . relativeRaw ( relative ) . packageOf ( packageOf ) . genericArgs ( generics ( ) . args ( ) ) . relativeAlreadyQualified ( relativeAlreadyQualified ) . visibility ( protoclass ( ) . visibility ( ) ) . build ( ) ; }

Actual abstract value type that is definitive model for the value type.
@return abstract value type name forms

Actual abstract value type that is definitive model for the value type .


private String inPackage(String topLevel, String... nested) {
    return DOT_JOINER.join(null, topLevel, (Object[]) nested);
  }

private String inPackage ( String topLevel , String ... nested ) { return DOT_JOINER . join ( null , topLevel , ( Object [ ] ) nested ) ; }

Package relative path
@param topLevel
@param nested
@return


@Value.Lazy
  public NameForms typeImmutable() {
    String simple, relative;

    if (protoclass().kind().isNested()) {
      String enclosingSimpleName = typeImmutableEnclosingSimpleName();
      simple = names().typeImmutableNested();
      relative = inPackage(enclosingSimpleName, simple);
    } else if (hasImmutableInBuilder()) {
      simple = names().typeImmutable;
      relative = inPackage(typeBuilderSimpleName(), simple);
    } else {
      simple = names().typeImmutable;
      relative = inPackage(simple);
    }

    return ImmutableConstitution.NameForms.builder()
        .simple(simple)
        .relativeRaw(relative)
        .genericArgs(generics().args())
        .packageOf(implementationPackage())
        .visibility(implementationVisibility())
        .build();
  }

@ Value . Lazy public NameForms typeImmutable ( ) { String simple , relative ; if ( protoclass ( ) . kind ( ) . isNested ( ) ) { String enclosingSimpleName = typeImmutableEnclosingSimpleName ( ) ; simple = names ( ) . typeImmutableNested ( ) ; relative = inPackage ( enclosingSimpleName , simple ) ; } else if ( hasImmutableInBuilder ( ) ) { simple = names ( ) . typeImmutable ; relative = inPackage ( typeBuilderSimpleName ( ) , simple ) ; } else { simple = names ( ) . typeImmutable ; relative = inPackage ( simple ) ; } return ImmutableConstitution . NameForms . builder ( ) . simple ( simple ) . relativeRaw ( relative ) . genericArgs ( generics ( ) . args ( ) ) . packageOf ( implementationPackage ( ) ) . visibility ( implementationVisibility ( ) ) . build ( ) ; }

Actual immutable value type generated implementation.
@return immutable implementation type name forms

Actual immutable value type generated implementation .


@SuppressWarnings("unchecked")
  @Override
  @Nullable
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (ID_TYPE_TOKEN.equals(type)) {
      return (TypeAdapter<T>) WRAPPED_ID_ADAPTER;
    }
    if (TIME_INSTANT_TYPE_TOKEN.equals(type)) {
      return (TypeAdapter<T>) WRAPPED_TIME_INSTANT_ADAPTER;
    }
    if (BINARY_TYPE_TOKEN.equals(type)) {
      return (TypeAdapter<T>) WRAPPED_BINARY_ADAPTER;
    }
    if (PATTERN_TYPE_TOKEN.equals(type)) {
      return (TypeAdapter<T>) PATTERN_ADAPTER;
    }
    if (DECIMAL128_TYPE_TOKEN.equals(type)) {
      return (TypeAdapter<T>) DECIMAL128_ADAPTER;
    }
    return null;
  }

@ SuppressWarnings ( "unchecked" ) @ Override @ Nullable public < T > TypeAdapter < T > create ( Gson gson , TypeToken < T > type ) { if ( ID_TYPE_TOKEN . equals ( type ) ) { return ( TypeAdapter < T > ) WRAPPED_ID_ADAPTER ; } if ( TIME_INSTANT_TYPE_TOKEN . equals ( type ) ) { return ( TypeAdapter < T > ) WRAPPED_TIME_INSTANT_ADAPTER ; } if ( BINARY_TYPE_TOKEN . equals ( type ) ) { return ( TypeAdapter < T > ) WRAPPED_BINARY_ADAPTER ; } if ( PATTERN_TYPE_TOKEN . equals ( type ) ) { return ( TypeAdapter < T > ) PATTERN_ADAPTER ; } if ( DECIMAL128_TYPE_TOKEN . equals ( type ) ) { return ( TypeAdapter < T > ) DECIMAL128_ADAPTER ; } return null ; }

safe unchecked, typecheck performed by type token equality

safe unchecked typecheck performed by type token equality


@SuppressWarnings("unchecked")
  public static <E extends OrdinalValue<E>> ImmutableOrdinalSet<E> of() {
    // safe unchecked: will contain no elements
    return (ImmutableOrdinalSet<E>) EMPTY_SET;
  }

Returns singleton empty immutable ordinal set
@param <E> element type
@return empty set


@Override
  public Iterator<E> iterator() {
    return new AbstractIterator<E>() {
      private final int length = length();
      private int index = 0;

      @Override
      protected E computeNext() {
        int p = index++;
        if (p < length) {
          return get(p);
        }
        return endOfData();
      }
    };
  }

@ Override public Iterator < E > iterator ( ) { return new AbstractIterator < E > ( ) { private final int length = length ( ) ; private int index = 0 ; @ Override protected E computeNext ( ) { int p = index ++ ; if ( p < length ) { return get ( p ) ; } return endOfData ( ) ; } } ; }

Iterator over all present inhabitants of ordinal domain.
@return snapshot iterator of elements in ordinal domain.

Iterator over all present inhabitants of ordinal domain .


private static String cachingKey(ValueAttribute valueAttribute) {
    return String.format("%s-%s",
        valueAttribute.containedTypeElement.getQualifiedName(),
        Joiner.on(".").join(valueAttribute.containingType.constitution.style().attributeBuilder()));
  }

private static String cachingKey ( ValueAttribute valueAttribute ) { return String . format ( "%s-%s" , valueAttribute . containedTypeElement . getQualifiedName ( ) , Joiner . on ( "." ) . join ( valueAttribute . containingType . constitution . style ( ) . attributeBuilder ( ) ) ) ; }

The same class included in two parents, may or may not be nested builders based on that discovery pattern

The same class included in two parents may or may not be nested builders based on that discovery pattern


public String getSerializedName() {
    if (serializedName == null) {
      Optional<SerializedNameMirror> serializedNameAnnotation = SerializedNameMirror.find(element);
      if (serializedNameAnnotation.isPresent()) {
        SerializedNameMirror m = serializedNameAnnotation.get();
        serializedName = m.value();
        alternateSerializedNames = m.alternate();
        return serializedName;
      }
      Optional<NamedMirror> namedAnnotation = NamedMirror.find(element);
      if (namedAnnotation.isPresent()) {
        String value = namedAnnotation.get().value();
        if (!value.isEmpty()) {
          serializedName = value;
          return serializedName;
        }
      }
      Optional<OkNamedMirror> okNamedAnnotation = OkNamedMirror.find(element);
      if (okNamedAnnotation.isPresent()) {
        String value = okNamedAnnotation.get().name();
        if (!value.isEmpty()) {
          serializedName = value;
          return serializedName;
        }
      }
      if (isMarkedAsMongoId()) {
        serializedName = ID_ATTRIBUTE_NAME;
        return serializedName;
      }
      serializedName = "";
      return serializedName;
    }
    return serializedName;
  }

public String getSerializedName ( ) { if ( serializedName == null ) { Optional < SerializedNameMirror > serializedNameAnnotation = SerializedNameMirror . find ( element ) ; if ( serializedNameAnnotation . isPresent ( ) ) { SerializedNameMirror m = serializedNameAnnotation . get ( ) ; serializedName = m . value ( ) ; alternateSerializedNames = m . alternate ( ) ; return serializedName ; } Optional < NamedMirror > namedAnnotation = NamedMirror . find ( element ) ; if ( namedAnnotation . isPresent ( ) ) { String value = namedAnnotation . get ( ) . value ( ) ; if ( ! value . isEmpty ( ) ) { serializedName = value ; return serializedName ; } } Optional < OkNamedMirror > okNamedAnnotation = OkNamedMirror . find ( element ) ; if ( okNamedAnnotation . isPresent ( ) ) { String value = okNamedAnnotation . get ( ) . name ( ) ; if ( ! value . isEmpty ( ) ) { serializedName = value ; return serializedName ; } } if ( isMarkedAsMongoId ( ) ) { serializedName = ID_ATTRIBUTE_NAME ; return serializedName ; } serializedName = "" ; return serializedName ; } return serializedName ; }

Serialized name, actully specified via annotation
@return name for JSON as overriden.

Serialized name actully specified via annotation


public String getMarshaledName() {
    String serializedName = getSerializedName();
    if (!serializedName.isEmpty()) {
      return serializedName;
    }
    return names.raw;
  }

public String getMarshaledName ( ) { String serializedName = getSerializedName ( ) ; if ( ! serializedName . isEmpty ( ) ) { return serializedName ; } return names . raw ; }

Marshaled name for compatibility with repository.
@return get JSON name either specified or default.

Marshaled name for compatibility with repository .


public static <T> Predicate<T> of(Expression<T> expression) {
    if (Expressions.isNil(expression)) {
      // always true
      return instance -> true;
    }

    return new InMemoryExpressionEvaluator<>(expression);
  }

public
static
<
T
>
Predicate
<
T
>
of
(
Expression
<
T
>
expression
)
{
if
(
Expressions
.
isNil
(
expression
)
)
{
// always true
return
instance
->
true
;
}
return
new
InMemoryExpressionEvaluator
<>
(
expression
)
;
}

Factory method to create evaluator instance


public static <V> FluentFuture<V> from(ListenableFuture<V> future) {
    if (future instanceof FluentFuture<?>) {
      return (FluentFuture<V>) future;
    }
    return new WrapingFluentFuture<>(future, MoreExecutors.directExecutor());
  }

public static < V > FluentFuture < V > from ( ListenableFuture < V > future ) { if ( future instanceof FluentFuture < ? > ) { return ( FluentFuture < V > ) future ; } return new WrapingFluentFuture <> ( future , MoreExecutors . directExecutor ( ) ) ; }

Wraps listenable future with a fluent future.
@param <V> value type
@param future future
@return fluent instance

Wraps listenable future with a fluent future .


@Encoding.Expose
  public Optional<ImmutableMap<K, V>> getImmutable() {
    return Optional.ofNullable(map);
  }

@ Encoding . Expose public Optional < ImmutableMap < K , V > > getImmutable ( ) { return Optional . ofNullable ( map ) ; }

alternatively it can be exposed as Optional of ImmutableMap


protected String stringify(DeclaredType input, TypevarContext context) {
    return toTypeElement(input).getQualifiedName().toString();
  }

protected String stringify ( DeclaredType input , TypevarContext context ) { return toTypeElement ( input ) . getQualifiedName ( ) . toString ( ) ; }

overridable stringify.
@param input the input
@param context the context
@return the string


public final TokenBuffer nextTokenBuffer() throws IOException {
    TokenBuffer buffer = new TokenBuffer(parser);
    // if token is consumed, but undelying parser is still sitting on this token, we move forward
    requirePeek();
    buffer.copyCurrentStructure(parser);
    // when we will return to reading from reader, state will be cleared and nextToken after
    clearPeek();
    return buffer;
  }

Reads current value including objects and array as effiecient token buffer.
Use of Jackson's own mechanisms is important to preserve custom elements
such as special embedded objects in BSON or other data formats.
@return {@link TokenBuffer}
@throws IOException if error occured

Reads current value including objects and array as effiecient token buffer . Use of Jackson s own mechanisms is important to preserve custom elements such as special embedded objects in BSON or other data formats .


void close() {
    lock.lock();
    condition.signal();
    setAutoAccept(true);
    lock.unlock();
    holder_ = null;
  }

void close ( ) { lock . lock ( ) ; condition . signal ( ) ; setAutoAccept ( true ) ; lock . unlock ( ) ; holder_ = null ; }


public Object execute(String scriptBody, Object[] parameters) {
    try {
      asyncResult = new AsyncScriptResult();
      Function function = createInjectedScriptFunction(scriptBody, asyncResult);

      try {
        page.executeJavaScriptFunction(function, function, parameters,
            page.getDocumentElement());
      } catch (ScriptException e) {
        throw new WebDriverException(e);
      }

      try {
        return asyncResult.waitForResult(timeoutMillis);
      } catch (InterruptedException e) {
        throw new WebDriverException(e);
      }
    }
    finally {
      asyncResult = null;
    }
  }

public Object execute ( String scriptBody , Object [ ] parameters ) { try { asyncResult = new AsyncScriptResult ( ) ; Function function = createInjectedScriptFunction ( scriptBody , asyncResult ) ; try { page . executeJavaScriptFunction ( function , function , parameters , page . getDocumentElement ( ) ) ; } catch ( ScriptException e ) { throw new WebDriverException ( e ) ; } try { return asyncResult . waitForResult ( timeoutMillis ) ; } catch ( InterruptedException e ) { throw new WebDriverException ( e ) ; } } finally { asyncResult = null ; } }

Injects an asynchronous script for execution and waits for its result.

@param scriptBody The script body.
@param parameters The script parameters, which can be referenced using the {@code arguments}
JavaScript object.
@return The script result.

Injects an asynchronous script for execution and waits for its result .


public void setProxySettings(Proxy proxy) {
    if (proxy == null || proxy.getProxyType() == Proxy.ProxyType.UNSPECIFIED) {
      return;
    }

    switch (proxy.getProxyType()) {
      case MANUAL:
        List<String> noProxyHosts = new ArrayList<>();
        String noProxy = proxy.getNoProxy();
        if (noProxy != null && !noProxy.isEmpty()) {
          String[] hosts = noProxy.split(",");
          for (String host : hosts) {
            if (host.trim().length() > 0) {
              noProxyHosts.add(host.trim());
            }
          }
        }

        String httpProxy = proxy.getHttpProxy();
        if (httpProxy != null && !httpProxy.isEmpty()) {
          String host = httpProxy;
          int port = 0;

          int index = httpProxy.indexOf(":");
          if (index != -1) {
            host = httpProxy.substring(0, index);
            port = Integer.parseInt(httpProxy.substring(index + 1));
          }

          setHTTPProxy(host, port, noProxyHosts);
        }

        String socksProxy = proxy.getSocksProxy();
        if (socksProxy != null && !socksProxy.isEmpty()) {
          String host = socksProxy;
          int port = 0;

          int index = socksProxy.indexOf(":");
          if (index != -1) {
            host = socksProxy.substring(0, index);
            port = Integer.parseInt(socksProxy.substring(index + 1));
          }

          setSocksProxy(host, port, noProxyHosts);
        }

        // sslProxy is not supported/implemented
        // ftpProxy is not supported/implemented

        break;

      case PAC:
        String pac = proxy.getProxyAutoconfigUrl();
        if (pac != null && !pac.isEmpty()) {
          setAutoProxy(pac);
        }
        break;

      default:
          break;
    }
  }

Set proxy for WebClient using Proxy.

@param proxy The proxy preferences.


public void setHTTPProxy(String host, int port, List<String> noProxyHosts) {
    proxyConfig = new ProxyConfig();
    proxyConfig.setProxyHost(host);
    proxyConfig.setProxyPort(port);
    if (noProxyHosts != null && noProxyHosts.size() > 0) {
      for (String noProxyHost : noProxyHosts) {
        proxyConfig.addHostsToProxyBypass(noProxyHost);
      }
    }
    getWebClient().getOptions().setProxyConfig(proxyConfig);
  }

public void setHTTPProxy ( String host , int port , List < String > noProxyHosts ) { proxyConfig = new ProxyConfig ( ) ; proxyConfig . setProxyHost ( host ) ; proxyConfig . setProxyPort ( port ) ; if ( noProxyHosts != null && noProxyHosts . size ( ) > 0 ) { for ( String noProxyHost : noProxyHosts ) { proxyConfig . addHostsToProxyBypass ( noProxyHost ) ; } } getWebClient ( ) . getOptions ( ) . setProxyConfig ( proxyConfig ) ; }

Sets HTTP proxy for WebClient with bypass proxy hosts

@param host The hostname of HTTP proxy
@param port The port of HTTP proxy, 0 means HTTP proxy w/o port
@param noProxyHosts The list of hosts which need to bypass HTTP proxy


public void setAutoProxy(String autoProxyUrl) {
    proxyConfig = new ProxyConfig();
    proxyConfig.setProxyAutoConfigUrl(autoProxyUrl);
    getWebClient().getOptions().setProxyConfig(proxyConfig);
  }

public void setAutoProxy ( String autoProxyUrl ) { proxyConfig = new ProxyConfig ( ) ; proxyConfig . setProxyAutoConfigUrl ( autoProxyUrl ) ; getWebClient ( ) . getOptions ( ) . setProxyConfig ( proxyConfig ) ; }

Sets Proxy Autoconfiguration URL for WebClient

@param autoProxyUrl The Proxy Autoconfiguration URL


public static BoxDeveloperEditionAPIConnection userClient(String userId) {
        if (userId == null) { //   session data has expired
            return null;
        }
        System.out.format("userClient called with userId %s \n\n", userId);
        try {
            BoxDeveloperEditionAPIConnection userClient = BoxDeveloperEditionAPIConnection.getAppUserConnection(
                    userId, CLIENT_ID, CLIENT_SECRET, jwtEncryptionPreferences, accessTokenCache);
            return userClient;
        } catch (BoxAPIException apiException) {
            apiException.printStackTrace();
            throw apiException;
        }
    }

public
static
BoxDeveloperEditionAPIConnection
userClient
(
String
userId
)
{
if
(
userId
==
)
{
//   session data has expired
return
;
}
System
.
out
.
format
(
"userClient called with userId %s \n\n"
,
userId
)
;
try
{
BoxDeveloperEditionAPIConnection
userClient
=
BoxDeveloperEditionAPIConnection
.
getAppUserConnection
(
userId
,
CLIENT_ID
,
CLIENT_SECRET
,
jwtEncryptionPreferences
,
accessTokenCache
)
;
return
userClient
;
}
catch
(
BoxAPIException
apiException
)
{
apiException
.
printStackTrace
(
)
;
throw
apiException
;
}
}

Get a BoxDeveloperEditionAPIConnection that can be used by an App user to access Box.

@param userId The UserId of a valid Box App User
@return BoxDeveloperEditionAPIConnection new Box Developer Edition connection with App User token

Get a BoxDeveloperEditionAPIConnection that can be used by an App user to access Box .


public void updateModifiedFieldsFromEntity(ProcessDefinitionEntity updatingProcessDefinition) {
    if (!this.key.equals(updatingProcessDefinition.key) || !this.deploymentId.equals(updatingProcessDefinition.deploymentId)) {
      throw new ProcessEngineException("Cannot update entity from an unrelated process definition");
    }

    // TODO: add a guard once the mismatch between revisions in deployment cache and database has been resolved
    this.revision = updatingProcessDefinition.revision;
    this.suspensionState = updatingProcessDefinition.suspensionState;

  }

Updates all modifiable fields from another process definition entity.
@param updatingProcessDefinition

Updates all modifiable fields from another process definition entity .


private void addFourEyesTaskListener(ActivityImpl activity) {
    UserTaskActivityBehavior userTaskActivityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior();

    boolean listenerAlreadyExists = false;

    // check that the listener wasn't added in the XML explicitly
    List<TaskListener> existingListeners = userTaskActivityBehavior.getTaskDefinition().getTaskListeners().get("complete");
    for (TaskListener taskListener : existingListeners) {
      if (taskListener instanceof ClassDelegate &&
          ((ClassDelegate)taskListener).getClassName().equals(TaskCompletionListener.class.getName())) {
        listenerAlreadyExists = true;
        logger.info(TaskCompletionListener.class.getSimpleName() + " was already explicitly added to usertask in the bpmn xml.");
        break;
      }
    }

    if (!listenerAlreadyExists) {
      logger.info("Adding " + TaskCompletionListener.class.getSimpleName() + " implicitly to usertask.");
      ClassDelegate taskListener = new ClassDelegate(TaskCompletionListener.class, null);
      userTaskActivityBehavior.getTaskDefinition().addTaskListener("complete", taskListener);
    }

  }

Add TaskListener on "complete" event generically every time, so we don't
have to add it in the XML.

Add TaskListener on complete event generically every time so we don t have to add it in the XML .


@PostDeploy
  public void deployProcessesToTenantEngines() {
    // copy the process definitions deployed to the default engine to all tenants
    for (ProcessEngine processEngine : BpmPlatform.getProcessEngineService().getProcessEngines()) {
      if (processEngine != BpmPlatform.getDefaultProcessEngine()) {
        TenantManager.deployDefaultProcessesToEngine(processEngine);
      }
    }
  }

private static final String PROCESS_DEFINITION_KEY = "tenantdemo-process-application";

private static final String PROCESS_DEFINITION_KEY = tenantdemo - process - application ;


private void checkTaskSelectedViaBridge() {
    String bridgeTaskId = (String) getSharedSessionAttribute(BRIDGE_TASK_ID);
    String selectedTaskId = (String) getSharedSessionAttribute(ASSOCIATED_TASK_ID);

    if (selectedTaskId == null && bridgeTaskId != null) {
      switchTaskId(bridgeTaskId);
    }
    if (selectedTaskId != null && bridgeTaskId != null && !selectedTaskId.equals(bridgeTaskId)) {
      // task switched, TODO: think about if correct like this
      switchTaskId(bridgeTaskId);
    }
  }

"lazy" load task if bridge state has changed in the meantime

lazy load task if bridge state has changed in the meantime


public static String getServletContextPath(
			ProcessEngine processEngine, String processDefinitionId) {

		return getServletContextPath(getProcessApplicationInfo(processEngine, processDefinitionId));
	}

public static String getServletContextPath ( ProcessEngine processEngine , String processDefinitionId ) { return getServletContextPath ( getProcessApplicationInfo ( processEngine , processDefinitionId ) ) ; }

Retrieve the servlet context path of a process definition from a known process engine.

Retrieve the servlet context path of a process definition from a known process engine .


public static String getServletContextPath(String processDefinitionId) {
		ProcessApplicationInfo processApplicationInfo = getProcessApplicationInfo(processDefinitionId);
		if (processApplicationInfo == null) {
			return null;
		}
		return processApplicationInfo.getProperties().get(
				ProcessApplicationInfo.PROP_SERVLET_CONTEXT_PATH);
	}

public static String getServletContextPath ( String processDefinitionId ) { ProcessApplicationInfo processApplicationInfo = getProcessApplicationInfo ( processDefinitionId ) ; if ( processApplicationInfo == null ) { return null ; } return processApplicationInfo . getProperties ( ) . get ( ProcessApplicationInfo . PROP_SERVLET_CONTEXT_PATH ) ; }

Retrieve the servlet context path of a process definition from any process engine.

Retrieve the servlet context path of a process definition from any process engine .


public static ProcessApplicationInfo getProcessApplicationInfo(
			ProcessEngine processEngine, String processDefinitionId) {
		ProcessDefinition processDefinition = processEngine.getRepositoryService().getProcessDefinition(processDefinitionId);

		// get the name of the process application that made the deployment
		String processApplicationName = processEngine.getManagementService()
				.getProcessApplicationForDeployment(processDefinition.getDeploymentId());

		if (processApplicationName == null) {
			// not a process application deployment
			return null;
		} else {
			ProcessApplicationService processApplicationService = BpmPlatform.getProcessApplicationService();
			return processApplicationService.getProcessApplicationInfo(processApplicationName);
		}
	}

Retrieve the application info of a process definition from a known process engine.

Retrieve the application info of a process definition from a known process engine .


public static ProcessApplicationInfo getProcessApplicationInfo(String processDefinitionId) {
		ProcessEngineService processEngineService = BpmPlatform.getProcessEngineService();
		ProcessApplicationService processAppService = BpmPlatform.getProcessApplicationService();
		// iterate over all process applications
		for (String appName : processAppService.getProcessApplicationNames()) {
			ProcessApplicationInfo appInfo = processAppService
					.getProcessApplicationInfo(appName);
			// iterate over all deployments of a process application
			for (ProcessApplicationDeploymentInfo deploymentInfo : appInfo
					.getDeploymentInfo()) {
				long count = processEngineService
						.getProcessEngine(deploymentInfo.getProcessEngineName())
						.getRepositoryService().createProcessDefinitionQuery()
						.deploymentId(deploymentInfo.getDeploymentId())
						.processDefinitionId(processDefinitionId).count();
				if (count > 0) {
					return appInfo;
				}
			}
		}
		return null;
	}

Retrieve the application info path of a process definition from any process engine.

Retrieve the application info path of a process definition from any process engine .


@SuppressWarnings("deprecation")
    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withDefaultPasswordEncoder().username("demo").password("demo").roles("ACTUATOR", "camunda-admin").build());
        manager.createUser(User.withDefaultPasswordEncoder().username("john").password("john").roles("camunda-user").build());
        return manager;
    }

@ SuppressWarnings ( "deprecation" ) @ Bean public UserDetailsService userDetailsService ( ) { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager ( ) ; manager . createUser ( User . withDefaultPasswordEncoder ( ) . username ( "demo" ) . password ( "demo" ) . roles ( "ACTUATOR" , "camunda-admin" ) . build ( ) ) ; manager . createUser ( User . withDefaultPasswordEncoder ( ) . username ( "john" ) . password ( "john" ) . roles ( "camunda-user" ) . build ( ) ) ; return manager ; }

In real world scenarios, this would be replaced by the actual IAM solution

In real world scenarios this would be replaced by the actual IAM solution


@SuppressWarnings("unchecked")
  public static final <T extends Serializable> T castValue(final Object value) {
    return value != null ? (T) value : null;
  }

@ SuppressWarnings ( "unchecked" ) public static final < T extends Serializable > T castValue ( final Object value ) { return value != null ? ( T ) value : null ; }

Type- and null-safe cast of variable-value.

Type - and null - safe cast of variable - value .