text:
NSString * const PBPREFERENCEPANE_FILES_NOTIFICATION_DEFAULTS_DIDCHANGE=@"filesDefaultsDidChange";

NSString * const PBPREFERENCEPANE_FILES_DEFAULPERMISSIONSMODE=@"Default Permissions Mode";

NSString * const PBPREFERENCEPANE_FILES_DEFAULTREFERENCESTYLE=@"Default Reference Style";

NSString * const PBPREFERENCEPANE_FILES_SHOWCUSTOMIZATIONDIALOG=@"Show Customization Dialog";

NSString * const PBPREFERENCEPANE_FILES_SPLITFORKSTOOLNAME=@"SplitForks Tool Name";

NSString * SPLITFORKSTOOL_GOLDIN=@"goldin";
NSString * SPLITFORKSTOOL_SPLITFORKS=@"SplitForks";

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.plugins.scala.lang.lexer;

import com.intellij.lexer.Lexer;
import com.intellij.lexer.LexerPosition;
import com.intellij.lexer.LexerState;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.xml.IXmlLeafElementType;
import com.intellij.psi.xml.XmlTokenType;
import com.intellij.util.containers.Stack;
import gnu.trove.TIntStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypesEx.*;

/**
 * @author ilyas
 */
public class ScalaLexer extends Lexer {

  protected final Lexer myScalaPlainLexer;
  private final Lexer myXmlLexer = new ScalaXmlTokenTypes.PatchedXmlLexer();

  protected Lexer myCurrentLexer;

  protected static final int MASK = 0x3F;
  protected static final int XML_SHIFT = 6;
  protected TIntStack myBraceStack = new TIntStack();
  protected Stack<Stack<MyOpenXmlTag>> myLayeredTagStack = new Stack<Stack<MyOpenXmlTag>>();

  protected int myBufferEnd;
  protected int myBufferStart;
  protected CharSequence myBuffer;
  protected int myXmlState;
  private int myTokenStart;
  private int myTokenEnd;
  private boolean inCdata = false;
  protected IElementType myTokenType;
  public final String XML_BEGIN_PATTERN = "<\\w";
  private int xmlSteps = -1;

  /* We need to store it as in some cases (e.g. when we have uninterrupted xml elements sequence like '')
   * when the last xml element was located in 'locateToken()' there is no way to determine from xml state/xml tags stack
   * that the lexer was inside xml. That means the lexer isn't able to patch state => the state can be == 0 =>
   * any incremental stuff (highlighting etc) can start lexical analysis from this position with 0 state => we get wrong token sequence
   */
  private IElementType previousToken = null;

  public ScalaLexer() {
    this(false);
  }

  public ScalaLexer(boolean treatDocCommentAsBlockComment) {
    myScalaPlainLexer = new ScalaLayeredPlainLexer(treatDocCommentAsBlockComment);
    myCurrentLexer = myScalaPlainLexer;
  }

  public void start(@NotNull CharSequence buffer, int startOffset, int endOffset, int initialState) {
    myCurrentLexer = myScalaPlainLexer;
    myCurrentLexer.start(buffer, startOffset, endOffset, initialState & MASK);
    myBraceStack.clear();
    myLayeredTagStack.clear();
    myXmlState = (initialState >> XML_SHIFT) & MASK;
    inCdata = false;
    xmlSteps = -1;
    myBuffer = buffer;
    myBufferStart = startOffset;
    myBufferEnd = endOffset;
    myTokenType = null;
  }

  public int getState() {
    locateToken();
    int state = 0;
    if (myLayeredTagStack.size() > 0) state = 239;
    if (myXmlState != 0 || isXmlTokenType(previousToken)) state = 239;
    int scalaState = myScalaPlainLexer.getState();
    if (scalaState != 0) state = 239;
    // work-around for the strange advance()-related assumption / behavior in locateToken()
    if (myTokenStart == 0) return 0;
    return state;
  }

  @Nullable
  public IElementType getTokenType() {
    locateToken();
    return myTokenType;
  }

  private void locateToken() {
    previousToken = myTokenType;

    if (myTokenType == null) {
      IElementType type = myCurrentLexer.getTokenType();
      int start = myCurrentLexer.getTokenStart();
      String tokenText = myCurrentLexer.getBufferSequence().subSequence(start, myCurrentLexer.getTokenEnd()).toString();
      if (myCurrentLexer == myXmlLexer && xmlSteps == 0) {
        myCurrentLexer = myScalaPlainLexer;
        myCurrentLexer.start(getBufferSequence(), start, myXmlLexer.getBufferEnd(), 0);
      }

      --xmlSteps;
      if (type == SCALA_XML_CONTENT_START) {
        final XmlTagValidator xmlTagValidator = new XmlTagValidator(myCurrentLexer);
        if (!xmlTagValidator.validate()) {
          xmlSteps = xmlTagValidator.step;
        }

        myCurrentLexer = myXmlLexer;
        myXmlState = 0;
        myCurrentLexer.start(getBufferSequence(), start, myBufferEnd, 0);
        myLayeredTagStack.push(new Stack<MyOpenXmlTag>());
        myLayeredTagStack.peek().push(new MyOpenXmlTag());
        myTokenType = myCurrentLexer.getTokenType();
        locateTextRange();
      } else if ((/*type == XML_ATTRIBUTE_VALUE_TOKEN || */type == ScalaXmlTokenTypes.XML_DATA_CHARACTERS()) && //todo: Dafuq???
          tokenText.startsWith("{") && !tokenText.startsWith("{{") && !inCdata) {
        myXmlState = myCurrentLexer.getState();
        (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start, myBufferEnd, 0);
        locateTextRange();
        myBraceStack.push(1);
        myTokenType = SCALA_IN_XML_INJECTION_START;
      } else if (type == ScalaTokenTypes.tRBRACE && myBraceStack.size() > 0) {
        int currentLayer = myBraceStack.pop();
        if (currentLayer == 1) {
          locateTextRange();
          (myCurrentLexer = myXmlLexer).start(getBufferSequence(), start + 1, myBufferEnd, myXmlState);
          myTokenType = SCALA_IN_XML_INJECTION_END;
        } else {
          myBraceStack.push(--currentLayer);
        }
      } else if (type == ScalaTokenTypes.tLBRACE && myBraceStack.size() > 0) {
        int currentLayer = myBraceStack.pop();
        myBraceStack.push(++currentLayer);
      } else if ((ScalaXmlTokenTypes.XML_START_TAG_START() == type || ScalaXmlTokenTypes.XML_COMMENT_START() == type
          || ScalaXmlTokenTypes.XML_CDATA_START() == type || ScalaXmlTokenTypes.XML_PI_START() == type) && !myLayeredTagStack.isEmpty()) {
        if (type == ScalaXmlTokenTypes.XML_CDATA_START()) {
          inCdata = true;
        }
        myLayeredTagStack.peek().push(new MyOpenXmlTag());
      } else if (ScalaXmlTokenTypes.XML_EMPTY_ELEMENT_END() == type && !myLayeredTagStack.isEmpty() &&
          !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == TAG_STATE.UNDEFINED) {

        myLayeredTagStack.peek().pop();
        if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) {
          myLayeredTagStack.pop();
          locateTextRange();
          startScalaPlainLexer(start + 2);
          myTokenType = ScalaXmlTokenTypes.XML_EMPTY_ELEMENT_END();
          return;
        }
      } else if (ScalaXmlTokenTypes.XML_TAG_END() == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty()) {
        MyOpenXmlTag tag = myLayeredTagStack.peek().peek();
        if (tag.state == TAG_STATE.UNDEFINED) {
          tag.state = TAG_STATE.NONEMPTY;
        } else if (tag.state == TAG_STATE.NONEMPTY) {
          myLayeredTagStack.peek().pop();
        }
        if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) {
          myLayeredTagStack.pop();
          locateTextRange();
          startScalaPlainLexer(start + 1);
          myTokenType = ScalaXmlTokenTypes.XML_TAG_END();
          return;
        }
      } else if (ScalaXmlTokenTypes.XML_PI_END() == type && !myLayeredTagStack.isEmpty() &&
          !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == TAG_STATE.UNDEFINED) {

        myLayeredTagStack.peek().pop();
        if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) {
          myLayeredTagStack.pop();
          locateTextRange();
          startScalaPlainLexer(start + 2);
          myTokenType = ScalaXmlTokenTypes.XML_PI_END();
          return;
        }
      } else if (ScalaXmlTokenTypes.XML_COMMENT_END() == type && !myLayeredTagStack.isEmpty() &&
          !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == TAG_STATE.UNDEFINED) {

        myLayeredTagStack.peek().pop();
        if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) {
          myLayeredTagStack.pop();
          locateTextRange();
          startScalaPlainLexer(start + 3);
          myTokenType = ScalaXmlTokenTypes.XML_COMMENT_END();
          return;
        }
      } else if (ScalaXmlTokenTypes.XML_CDATA_END() == type && !myLayeredTagStack.isEmpty() &&
          !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == TAG_STATE.UNDEFINED) {
        inCdata = false;
        myLayeredTagStack.peek().pop();
        if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) {
          myLayeredTagStack.pop();
          locateTextRange();
          startScalaPlainLexer(start + 3);
          myTokenType = ScalaXmlTokenTypes.XML_CDATA_END();
          return;
        }
      } else if (type == ScalaXmlTokenTypes.XML_DATA_CHARACTERS() && tokenText.indexOf('{') != -1 && !inCdata) {
        int scalaToken = tokenText.indexOf('{');
        while (scalaToken != -1 && scalaToken + 1 < tokenText.length() && tokenText.charAt(scalaToken + 1) == '{')
          scalaToken = tokenText.indexOf('{', scalaToken + 2);
        if (scalaToken != -1) {
          myTokenType = ScalaXmlTokenTypes.XML_DATA_CHARACTERS();
          myTokenStart = myCurrentLexer.getTokenStart();
          myTokenEnd = myTokenStart + scalaToken;
          myCurrentLexer.start(getBufferSequence(), myTokenEnd, myBufferEnd, myCurrentLexer.getState());
        }
      } else if ((type == XmlTokenType.XML_REAL_WHITE_SPACE ||
          type == XmlTokenType.XML_WHITE_SPACE ||
          type == XmlTokenType.TAG_WHITE_SPACE) &&
          tokenText.matches("\\s*\n(\n|\\s)*")) {
        type = ScalaTokenTypes.tWHITE_SPACE_IN_LINE;
      } else if (type == null || !(type instanceof IXmlLeafElementType) && !ScalaXmlTokenTypes.isSubstituted(type.toString())) {
        ++xmlSteps;
      }
      if (myTokenType == null) {
        myTokenType = type;
        if (myTokenType == null) return;
        locateTextRange();
      }
      //we have to advance current lexer only if we didn't start scala plain lexer on this iteration
      //because of wrong behaviour of the latter ScalaPlainLexer
      myCurrentLexer.advance();
    }
  }

  private void startScalaPlainLexer(int start) {
    (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start, myBufferEnd);
  }

  private void locateTextRange() {
    myTokenStart = myCurrentLexer.getTokenStart();
    myTokenEnd = myCurrentLexer.getTokenEnd();
  }

  private boolean checkNotNextXmlBegin(Lexer lexer) {
    String text = lexer.getBufferSequence().toString();
    int beginIndex = lexer.getTokenEnd();
    if (beginIndex < text.length()) {
      text = text.substring(beginIndex).trim();
      if (text.length() > 2) {
        text = text.substring(0, 2);
      }
      return !text.matches(XML_BEGIN_PATTERN);
    }
    return true;
  }

  public int getTokenStart() {
    locateToken();
    if (myTokenType == null) return myTokenEnd;
    return myTokenStart;
  }

  public int getTokenEnd() {
    locateToken();
    return myTokenEnd;
  }

  public void advance() {
    myTokenType = null;
  }

  @NotNull
  public LexerPosition getCurrentPosition() {
    return new MyPosition(
        myTokenStart,
        myTokenEnd,
        new MyState(
            myXmlState,
            0,
            myBraceStack,
            myCurrentLexer,
            myLayeredTagStack));
  }

  public void restore(@NotNull LexerPosition position) {
    MyPosition pos = (MyPosition) position;
    myBraceStack = pos.state.braceStack;
    myCurrentLexer = pos.state.currentLexer;
    myTokenStart = pos.getOffset();
    myTokenEnd = pos.end;
    myLayeredTagStack = pos.state.tagStack;
    myCurrentLexer.start(myCurrentLexer.getBufferSequence(), myTokenStart, myBufferEnd,
        myCurrentLexer instanceof ScalaXmlTokenTypes.PatchedXmlLexer ? pos.state.xmlState : 0);
  }

  @NotNull
  public CharSequence getBufferSequence() {
    return myBuffer;
  }

  public int getBufferEnd() {
    return myBufferEnd;
  }

  private boolean isXmlTokenType(IElementType tpe) {
    return tpe != null && ScalaXmlTokenTypes.XML_ELEMENTS().contains(tpe);
  }

  private static class MyState implements LexerState {

    public TIntStack braceStack;
    public Stack<Stack<MyOpenXmlTag>> tagStack;
    public Lexer currentLexer;
    public int xmlState;
    public int scalaState;

    public MyState(final int xmlState, final int scalaState, TIntStack braceStack, Lexer lexer, Stack<Stack<MyOpenXmlTag>> tagStack) {
      this.braceStack = braceStack;
      this.tagStack = tagStack;
      this.currentLexer = lexer;
      this.xmlState = xmlState;
      this.scalaState = scalaState;
    }

    public short intern() {
      return 0;
    }
  }

  private static class MyPosition implements LexerPosition {
    public int start;
    public int end;
    public MyState state;

    public MyPosition(final int start, final int end, final MyState state) {
      this.start = start;
      this.end = end;
      this.state = state;
    }

    public int getOffset() {
      return start;
    }

    public int getState() {
      return state.currentLexer.getState();
    }
  }

  protected enum TAG_STATE {
    UNDEFINED, EMPTY, NONEMPTY
  }

  private static class MyOpenXmlTag {
    public TAG_STATE state = TAG_STATE.UNDEFINED;
  }

  private static class XmlTagValidator {
    final private static List<IElementType> allStopTokens =
        Arrays.<IElementType>asList(ScalaXmlTokenTypes.XML_TAG_END(), ScalaXmlTokenTypes.XML_EMPTY_ELEMENT_END(), ScalaXmlTokenTypes.XML_PI_END(),
            ScalaXmlTokenTypes.XML_COMMENT_END(), null, ScalaXmlTokenTypes.XML_START_TAG_START());
    final private static List<IElementType> validStopTokens = Arrays.<IElementType>asList(ScalaXmlTokenTypes.XML_TAG_END(),
        ScalaXmlTokenTypes.XML_EMPTY_ELEMENT_END(), ScalaXmlTokenTypes.XML_PI_END(), ScalaXmlTokenTypes.XML_COMMENT_END());

    final private Lexer lexer;
    final private LinkedList<IElementType> xmlTokens;
    final private ScalaXmlTokenTypes.PatchedXmlLexer valLexer;
    private int step = 0;

    private XmlTagValidator(Lexer lexer) {
      this.lexer = lexer;
      xmlTokens = new LinkedList<IElementType>();
      valLexer = new ScalaXmlTokenTypes.PatchedXmlLexer();
    }

    private boolean validate() {
      valLexer.start(lexer.getBufferSequence(), lexer.getTokenStart(), lexer.getBufferEnd(), 0);
      step = 0;

      boolean isCdata = valLexer.getTokenType() == ScalaXmlTokenTypes.XML_CDATA_START();

      advanceLexer();
      step = 1;

      if (!isCdata) {
        while (canProcess()) {
          if (valLexer.getTokenType() == ScalaXmlTokenTypes.XML_DATA_CHARACTERS()) {
              return xmlTokens.peekLast() == ScalaXmlTokenTypes.XML_EQ() && valLexer.getTokenText().startsWith("{") &&
                      !valLexer.getTokenText().startsWith("{{");
          } else {
            advanceLexer();
          }
        }

        return validStopTokens.contains(valLexer.getTokenType());
      }

      if (valLexer.getTokenType() == ScalaXmlTokenTypes.XML_CDATA_END()) return true;
      advanceLexer();
      return valLexer.getTokenType() == ScalaXmlTokenTypes.XML_CDATA_END();
    }

    private void advanceLexer() {
      xmlTokens.addLast(valLexer.getTokenType());
      valLexer.advance();
      ++step;
    }

    private boolean canProcess() {
      if (allStopTokens.contains(valLexer.getTokenType())) return false;

      if (valLexer.getTokenType() == ScalaXmlTokenTypes.XML_NAME()) {
        if (xmlTokens.size() == 1) return true;
        if (xmlTokens.peekLast() != XmlTokenType.XML_WHITE_SPACE) return false;
        xmlTokens.pollLast();

        if (xmlTokens.peekLast() == ScalaXmlTokenTypes.XML_NAME()) {
          return xmlTokens.size() == 2;
        }

        return xmlTokens.peekLast() == ScalaXmlTokenTypes.XML_ATTRIBUTE_VALUE_END_DELIMITER();
      } else {
        return true;
      }
    }
  }
}


text:
#ifndef LCS_H_
#define LCS_H_

/**\file LCS.h
 * \brief Classe que calcula a maior subsequência comum entre duas strings.
 *
 * @version CAL1011_2MIEIC6_8_TG2_1 - 10-11 - MIEIC
 * @author Carlos Miguel Correia da Costa - ei09097
 */

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using std::string;
using std::vector;
using std::cout;
using std::endl;
using std::max;
using std::reverse;

//################################################################   LCS   #######################################################################
/**
 * Classe que calcula a maior subsequência comum entre duas strings.
 */
class LCS {
private:
//=============================================================   <private>   ====================================================================
	string text;
	string pattern;

	string textOptimized;
	string patternOptimized;

	size_t textAndPatternInitialIndex;
	size_t textFinalIndex;
	size_t patternFinalIndex;

	string LCSFound;

	vector < vector <int> > subSequenceLengths;
	bool subSequenceLengthsValid;
//=============================================================   </private>   ===================================================================

public:
//==============================================================   <public>   ====================================================================

	//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <constructors-destructors>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	/// Default constructor de LCS
	LCS();

	/**
	 * Contructor de LCS
	 * @param _text texto que será analisado
	 * @param _pattern padrão que será usado nessa análise
	 */
	LCS(string _text, string _pattern);

	/// Default destructor de LCS
	virtual ~LCS();
	//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </constructors-destructors>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <algoritmos de LCS>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
	/// Método que optimiza o algoritmo calcLCS(), tirando as partes comuns no inicio e fim de cada uma das strings
	void optimizeStringsToAnalize();

	/**
	 * Método que calcula a maior subcadeia comum das duas subtrings passadas no constructor
	 * @return Matrix com as distâncias ce edição
	 */
	vector < vector<int> >& calcLCS();

	/**
	 * Determinação da LCS usando a matriz calculada em calcLCS()
	 * @return LCS das duas strings
	 */
	string findLCS();

	/// Método que permite mostrar a matriz determinada por calcLCS() para poder confirmar o correcto funcuionamento do programa
	void showSubSequenceLengths();
	//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </algoritmos de LCS>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <gets>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    string getLCSFound() const;
    string getPattern() const;
    size_t getPatternFinalIndex() const;
    string getPatternOptimized() const;
    vector<vector<int> > getSubSequenceLengths() const;
    bool getSubSequenceLengthsValid() const;
    string getText() const;
    size_t getTextAndPatternInitialIndex() const;
    size_t getTextFinalIndex() const;
    string getTextOptimized() const;
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </gets>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <sets>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    void setLCSFound(string LCSFound);
    void setPattern(string pattern);
    void setPatternFinalIndex(size_t patternFinalIndex);
    void setPatternOptimized(string patternOptimized);
    void setSubSequenceLengths(vector<vector<int> > subSequenceLengths);
    void setSubSequenceLengthsValid(bool subSequenceLengthsValid);
    void setText(string text);
    void setTextAndPatternInitialIndex(size_t textAndPatternInitialIndex);
    void setTextFinalIndex(size_t textFinalIndex);
    void setTextOptimized(string textOptimized);
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   </sets>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
};

#endif /* LCS_H_ */


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>tbb::flow::interface7::continue_node< Output > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

tbb

flow

interface7

continue_node

Public Types |
Public Member Functions |
Protected Member Functions |
Friends |
List of all members

tbb::flow::interface7::continue_node< Output > Class Template Reference

Implements an executable node that supports continue_msg -> Output.
 More...

#include <flow_graph.h>

Inheritance diagram for tbb::flow::interface7::continue_node< Output >:

  <map id="tbb::flow::interface7::continue_node< Output >_map" name="tbb::flow::interface7::continue_node< Output >_map">
<area href="a00069.html" title="The base of all graph nodes. " alt="tbb::flow::interface7::graph_node" shape="rect" coords="0,56,271,80"/>
</map>

Public Types

typedef continue_msg 	input_type

typedef Output 	output_type

typedef sender< input_type > 	predecessor_type

typedef receiver< output_type > 	successor_type

typedef

internal::continue_input

< Output > 	fInput_type

typedef

internal::function_output

< output_type > 	fOutput_type

Public Member Functions

template<typename Body >

 	continue_node (graph &g, Body body)

 	Constructor for executable node with continue_msg -> Output.

template<typename Body >

 	continue_node (graph &g, int number_of_predecessors, Body body)

 	Constructor for executable node with continue_msg -> Output.

 	continue_node (const continue_node &src)

 	Copy constructor.

void 	set_name (const char *name)

 Public Member Functions inherited from tbb::flow::interface7::graph_node

 	graph_node (graph &g)

virtual void 	extract (reset_flags f=rf_extract)

Protected Member Functions

void 	reset (__TBB_PFG_RESET_ARG(reset_flags f))

internal::broadcast_cache

< output_type > & 	successors ()

 Protected Member Functions inherited from tbb::flow::interface7::graph_node

virtual void 	reset (__TBB_PFG_RESET_ARG(reset_flags f=rf_reset_protocol))=0

Friends

template<typename R , typename B >

class 	run_and_put_task

template<typename X , typename Y >

class 	internal::broadcast_cache

template<typename X , typename Y >

class 	internal::round_robin_cache

Additional Inherited Members

 Protected Attributes inherited from tbb::flow::interface7::graph_node

graph & 	my_graph

graph_node * 	next

graph_node * 	prev

Detailed Description

template<typename Output>

class tbb::flow::interface7::continue_node< Output >

Implements an executable node that supports continue_msg -> Output.

The documentation for this class was generated from the following file:

flow_graph.h

Copyright © 2005-2015 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
// Copyright 2020 by PeopleWare n.v..
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

using JetBrains.Annotations;

using NHibernate.Mapping.ByCode;

using PPWCode.Vernacular.NHibernate.III.MappingByCode;
using PPWCode.Vernacular.Persistence.IV;

namespace PPWCode.Vernacular.NHibernate.III.Tests.Model.RepositoryWithDtoMapping
{
    [Serializable]
    [DataContract(IsReference = true)]
    public class Ship : PersistentObject<int>
    {
        [DataMember]
        private readonly ISet<CargoContainer> _cargoContainers = new HashSet<CargoContainer>();

        public Ship()
        {
        }

        public Ship(int id)
            : base(id)
        {
        }

        [DataMember]
        public virtual string Code { get; set; }

        [AuditLogPropertyIgnore]
        public virtual ISet<CargoContainer> CargoContainers
            => _cargoContainers;

        public virtual void AddCargoContainer(CargoContainer cargoContainer)
        {
            if ((cargoContainer != null) && CargoContainers.Add(cargoContainer))
            {
                cargoContainer.Ship = this;
            }
        }

        public virtual void RemoveCargoContainer(CargoContainer cargoContainer)
        {
            if ((cargoContainer != null) && CargoContainers.Remove(cargoContainer))
            {
                cargoContainer.Ship = null;
            }
        }
    }

    [UsedImplicitly]
    public class ShipMapper : PersistentObjectMapper<Ship, int>
    {
        public ShipMapper()
        {
            Property(s => s.Code);

            Set(
                s => s.CargoContainers,
                m => m.Cascade(Cascade.All | Cascade.Merge),
                r => r.OneToMany());
        }
    }
}


text:
using namespace std;

vector<vector<int>> FindLeavesOfBinaryTree::findLeaves(TreeNode *root) {
    vector<vector<int>> ret;
    height(root, ret);
    return ret;
}

int FindLeavesOfBinaryTree::height(TreeNode *root, vector<vector<int>> &ret) {
    if (root == nullptr) return -1;
    int level = 1 + max(height(root->left, ret), height(root->right, ret));
    if (ret.size() < level + 1) ret.push_back(vector<int>(0));
    ret[level].push_back(root->val);
    return level;
}


text:
require 'test_helper'

class LessonVersionsControllerTest < ActionController::TestCase
  test "should get show" do
    get :show
    assert_response :success
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should get edit" do
    get :edit
    assert_response :success
  end

end


text:
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.Shell.Interop;

namespace PSycheTest.Runners.VisualStudio.Core
{
	/// <summary>
	/// Provides information about an <see cref="IVsSolution"/>.
	/// </summary>
	public interface ISolutionInfo
	{
		/// <summary>
		/// Iterates over the projects in an <see cref="IVsSolution"/>.
		/// </summary>
		IEnumerable<IVsProject> GetProjects();

		/// <summary>
		/// Returns the directory a solution is in.
		/// </summary>
		DirectoryInfo GetDirectory();
	}
}


text:
<?php
namespace app\modules\banners\modules\admin;

use common\core\AdminModule;

/**
 * Class Admin
 * Административный модуль баннерного модуля
 * @package app\modules\banners\modules\admin
 * @author Churkin Anton <webadmin87@gmail.com>
 */
class Admin extends AdminModule
{

}


text:
import { useCallback } from 'react';

import { getMemberAndAddress } from '@proton/shared/lib/calendar/members';
import { GetCalendarInfo } from '@proton/shared/lib/interfaces/hooks/GetCalendarInfo';

import { useGetAddresses } from './useAddresses';
import { useGetAddressKeys } from './useGetAddressKeys';
import { useGetCalendarBootstrap } from './useGetCalendarBootstrap';
import { useGetDecryptedPassphraseAndCalendarKeys } from './useGetDecryptedPassphraseAndCalendarKeys';

export const useGetCalendarInfo = (): GetCalendarInfo => {
    const getCalendarBootstrap = useGetCalendarBootstrap();
    const getAddresses = useGetAddresses();
    const getDecryptedPassphraseAndCalendarKeys = useGetDecryptedPassphraseAndCalendarKeys();
    const getAddressKeys = useGetAddressKeys();

    return useCallback(
        async (calendarID: string) => {
            const [{ Members, CalendarSettings: calendarSettings }, Addresses] = await Promise.all([
                getCalendarBootstrap(calendarID),
                getAddresses(),
            ]);

            const [{ ID: memberID }, { ID: addressID }] = getMemberAndAddress(Addresses, Members);

            const { decryptedCalendarKeys, decryptedPassphrase, passphraseID } =
                await getDecryptedPassphraseAndCalendarKeys(calendarID);

            const addressKeys = await getAddressKeys(addressID);

            return {
                memberID,
                addressID,
                addressKeys,
                calendarKeys: decryptedCalendarKeys,
                calendarSettings,
                passphrase: decryptedPassphrase,
                passphraseID,
            };
        },
        [getCalendarBootstrap, getAddresses, getDecryptedPassphraseAndCalendarKeys, getAddressKeys]
    );
};

export default useGetCalendarInfo;


text:
package com.salesforce.dva.argus.entity;

import static com.salesforce.dva.argus.system.SystemAssert.requireArgument;
import static com.salesforce.dva.argus.system.SystemAssert.requireArgumentP;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Arrays;
import java.util.stream.Collectors;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.NoResultException;
import javax.persistence.OneToMany;
import javax.persistence.Query;
import javax.persistence.Table;
import javax.persistence.TemporalType;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.UniqueConstraint;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import com.salesforce.dva.argus.util.CommonUtils;
import com.salesforce.dva.argus.util.Cron;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.salesforce.dva.argus.service.metric.MetricReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The entity which encapsulates information about a Dashboard.
 *
 *
Fields that determine uniqueness are:

 *
 *

 *
ALERT_NAME

 *
OWNER

 *

 *
 *
Fields that cannot be null are:

 *
 *

 *
ALERT_NAME

 *
OWNER

 *

 *
 * @author  Tom Valine (tvaline@salesforce.com)
 * @author  Raj Sarkapally (rsarkapally@salesforce.com)
 * @author	Bhinav Sura (bhinav.sura@salesforce.com)
 * @author  Dongpu Jin (djin@salesforce.com)
 */
@SuppressWarnings("serial")
@Entity
@Table(name = "ALERT", uniqueConstraints = @UniqueConstraint(columnNames = { "name", "owner_id" }))
@NamedQueries(
		{
			@NamedQuery(
					name = "Alert.findByNameAndOwner",
					query =
					"SELECT a FROM Alert a WHERE a.name = :name AND a.owner = :owner AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL))"
					),
			@NamedQuery(
					name = "Alert.findByOwner",
					query = "SELECT a FROM Alert a WHERE a.owner = :owner AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL))"
					),
			@NamedQuery(
					name = "Alert.findAll", query = "SELECT a FROM Alert a WHERE a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL))"
					),
			@NamedQuery(
					name = "Alert.findByStatus",
					query = "SELECT a FROM Alert a where a.enabled= :enabled AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false and TYPE(jpa)= Alert AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL)) order by a.id asc"
					),
			@NamedQuery(
					name = "Alert.findByRangeAndStatus",
					query = "SELECT a FROM Alert a where a.id BETWEEN :fromId and :toId AND a.enabled= :enabled AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false and TYPE(jpa)= Alert AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL)) order by a.id asc"
					),
			@NamedQuery(
					name = "Alert.findIDsByStatus",
					query = "SELECT a.id FROM Alert a where a.enabled= :enabled AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false and TYPE(jpa)= Alert AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL)) order by a.id asc"
					),
			@NamedQuery(
					name = "Alert.findAlertsModifiedAfterDate",
					query = "SELECT a FROM Alert a where a.id in (SELECT jpa.id from JPAEntity jpa where TYPE(jpa)= Alert and jpa.modifiedDate >= :modifiedDate AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL)) order by a.id asc"
					),
			@NamedQuery(
					name = "Alert.findByPrefix",
					query = "SELECT a FROM Alert a where a.name LIKE :name AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL))"
					),
			@NamedQuery(name = "Alert.setEnabled", query = "UPDATE Alert a SET a.enabled=true WHERE a = :alert"),
			@NamedQuery(name = "Alert.setDisabled", query = "UPDATE Alert a SET a.enabled=false WHERE a = :alert"),
			@NamedQuery(name = "Alert.countByStatus", query = "SELECT count(a) from Alert a where a.enabled= :enabled"),
			@NamedQuery(
					name = "Alert.getSharedAlerts",
					query = "SELECT a from Alert a where a.shared = true AND a.id not in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = true)"
					),
			@NamedQuery(
					name = "Alert.getSharedAlertsByOwner",
					query = "SELECT a from Alert a where a.owner = :owner AND a.shared = true AND a.id not in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = true)"
					),
			// Count alert queries
			@NamedQuery(
					name = "Alert.countByOwner",
					query = "SELECT count(a) FROM Alert a WHERE a.owner = :owner AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL))"
					),
			@NamedQuery(
					name = "Alert.countByOwnerWithSearchText",
					query = "SELECT count(a) FROM Alert a WHERE a.owner = :owner AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL)) "
							+ "AND (FUNCTION('LOWER', a.name) LIKE :searchtext OR FUNCTION('LOWER', a.owner.userName) LIKE :searchtext)"
					),
			@NamedQuery(
					name = "Alert.countSharedAlerts",
					query = "SELECT count(a) from Alert a where a.shared = true AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL))"
					),
			@NamedQuery(
					name = "Alert.countSharedAlertsWithSearchText",
					query = "SELECT count(a) FROM Alert a WHERE a.shared = true AND a.id IN (SELECT jpa.id FROM JPAEntity jpa WHERE jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL)) "
							+ "AND (FUNCTION('LOWER', a.name) LIKE :searchtext OR FUNCTION('LOWER', a.owner.userName) LIKE :searchtext)"
					),
			@NamedQuery(
					name = "Alert.countPrivateAlertsForPrivilegedUser",
					query = "SELECT count(a) from Alert a where a.shared = false AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL))"
					),
			@NamedQuery(
					name = "Alert.countPrivateAlertsForPrivilegedUserWithSearchText",
					query = "SELECT count(a) from Alert a where a.shared = false AND a.id in (SELECT jpa.id from JPAEntity jpa where jpa.deleted = false AND (jpa.createdBy IS NOT NULL AND jpa.modifiedBy IS NOT NULL)) "
							+ "AND (FUNCTION('LOWER', a.name) LIKE :searchtext OR FUNCTION('LOWER', a.owner.userName) LIKE :searchtext)"
					),
		}
		)
public class Alert extends JPAEntity implements Serializable, CronJob {

	//~ Instance fields ******************************************************************************************************************************

	@Basic(optional = false)
	@Column(name = "name")
	@Metadata
	private String name;

	@Basic(optional = false)
	@Column(length = 2048)
	@Metadata
	private String expression;

	@Metadata
	@Basic(optional = false)
	private String cronEntry;

	@Metadata
	private boolean enabled = false;

	@Metadata
	private boolean missingDataNotificationEnabled;

	@OneToMany(mappedBy = "alert", cascade = CascadeType.ALL, orphanRemoval = true)
	private List<Notification> notifications = new ArrayList<>(0);

	@OneToMany(mappedBy = "alert", cascade = CascadeType.ALL, orphanRemoval = true)
	private List<Trigger> triggers = new ArrayList<>(0);

	@ManyToOne(optional = false)
	@JoinColumn(name = "owner_id", nullable = false)
	@Metadata
	private PrincipalUser owner;

	@Metadata
	private boolean shared;

	//~ Static Instance fields ***********************************************************************************************************************
	private static final Logger LOGGER = LoggerFactory.getLogger(Alert.class);

	// Default values for page limit and page offset
	private static int DEFAULT_PAGE_LIMIT = 10;
	private static int DEFAULT_PAGE_OFFSET = 0;

	// WHERE condition key names used in criteria queries
	private static String DELETED_KEY = "deleted";
	private static String SHARED_KEY = "shared";
	private static String OWNER_KEY = "owner";
	private static String SEARCHTEXT_KEY = "searchtext";

	//~ Constructors *********************************************************************************************************************************

	/**
	 * Creates a new Alert object.
	 *
	 * @param  creator     The creator of the alert.
	 * @param  owner       The owner of the alert. Cannot be null.
	 * @param  name        The name of the alert. Cannot be null or empty.
	 * @param  expression  The expression to evaluate triggers against. Cannot be null or empty and must be a valid metric expression as defined by
	 *                     the <tt>MetricService</tt>.
	 * @param  cronEntry   The CRON schedule for the alert. Cannot be null or empty and must be valid CRON entry syntax.
	 */
	public Alert(PrincipalUser creator, PrincipalUser owner, String name, String expression, String cronEntry) {
		super(creator);
		setOwner(owner);
		setName(name);
		setExpression(expression);
		setCronEntry(cronEntry);
		setMissingDataNotificationEnabled(false);
		setShared(false);
		setEnabled(false);
	}

	/**
	 * Creates an alert object by creating a deep copy of another alert
	 *
	 * @param  other       The alert to be copied
	 * @param  user        The owner of the new alert. Cannot be null.
	 * @param  alertName   The name of the new alert. Cannot be null or empty.
	 *
	 * @throws  Exception  Throws exception if a problem is encountered while copying props of the original alert.
	 */
	public Alert(Alert other, String alertName, PrincipalUser user) throws Exception {
		this(user, user, alertName, other.getExpression(), other.getCronEntry());

		List<Trigger> clonedTriggers = new ArrayList<>();
		List<Notification> clonedNotifications = new ArrayList<>();
		Map<Integer, Trigger> triggersCreatedMapByHash = new HashMap<>();

		/*For each existing notification, create new cloned notification.
		 * For each existing trigger in the current notification, create new cloned trigger and add it to cloned notification.
		 **/
		for (Notification currentNotification : other.getNotifications()) {
			Notification currentNotificationCloned = new Notification(
					currentNotification.getName(),
					this,
					currentNotification.getNotifierName(),
					currentNotification.getSubscriptions(),
					currentNotification.getCooldownPeriod()
			);

			clonedNotifications.add(currentNotificationCloned);

			CommonUtils.copyProperties(currentNotificationCloned, currentNotification);
			currentNotificationCloned.setAlert(this);
			currentNotificationCloned.setCreatedBy(user);
			currentNotificationCloned.setModifiedBy(user);

			List<Trigger> triggersInCurrentNotification = new ArrayList<>();
			for (Trigger currentTrigger : currentNotification.getTriggers()) {
				int currentTriggerHash = currentTrigger.hashCode();
				if (!triggersCreatedMapByHash.containsKey(currentTriggerHash)) {
					Trigger currentTriggerCloned = new Trigger(
							this,
							currentTrigger.getType(),
							currentTrigger.getName(),
							currentTrigger.getThreshold(),
							currentTrigger.getSecondaryThreshold(),
							currentTrigger.getInertia()
					);
					clonedTriggers.add(currentTriggerCloned);
					CommonUtils.copyProperties(currentTriggerCloned, currentTrigger);
					currentTriggerCloned.setCreatedBy(user);
					currentTriggerCloned.setModifiedBy(user);
					currentTriggerCloned.setAlert(this);
					triggersCreatedMapByHash.put(currentTriggerHash, currentTriggerCloned);
				}
				triggersInCurrentNotification.add(triggersCreatedMapByHash.get(currentTriggerHash));
			}
			currentNotificationCloned.setTriggers(triggersInCurrentNotification);
		}

		/*
		 * Triggers with no notifications attached
		 * */
		for (Trigger currentTrigger : other.getTriggers()) {
			int currentTriggerHash = currentTrigger.hashCode();
			if (!triggersCreatedMapByHash.containsKey(currentTriggerHash)) {
				Trigger currentTriggerCloned = new Trigger(
						this,
						currentTrigger.getType(),
						currentTrigger.getName(),
						currentTrigger.getThreshold(),
						currentTrigger.getSecondaryThreshold(),
						currentTrigger.getInertia()
				);
				clonedTriggers.add(currentTriggerCloned);
				CommonUtils.copyProperties(currentTriggerCloned, currentTrigger);
				currentTriggerCloned.setCreatedBy(user);
				currentTriggerCloned.setModifiedBy(user);
				currentTriggerCloned.setAlert(this);
				triggersCreatedMapByHash.put(currentTriggerHash, currentTriggerCloned);
			}
		}

		// NOTE: whenever a new field gets added to an Alert object make sure to update this clone
		this.setMissingDataNotificationEnabled(other.isMissingDataNotificationEnabled());
		this.setShared(other.isShared());
		this.setTriggers(clonedTriggers);
		this.setNotifications(clonedNotifications);
		this.setModifiedBy(user);
		this.setEnabled(other.isEnabled()); // This should be last
	}

	/** Creates a new Alert object. */
	protected Alert() {
		super(null);
	}

	//~ Methods **************************************************************************************************************************************

	/**
	 * Enables or disables an alert.
	 *
	 * @param  em       The entity manager to use. Cannot be null.
	 * @param  alert    The alert to use. Cannot be null.
	 * @param  enabled  True if enabled, false if disabled.
	 */
	public static void setEnabled(EntityManager em, Alert alert, boolean enabled) {
		requireArgument(em != null, "Entity manager can not be null.");
		requireArgument(alert != null, "Alert cannot be null.");

		Query query = em.createNamedQuery(enabled ? "Alert.setEnabled" : "Alert.setDisabled");
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		query.setParameter("alert", alert);
		query.executeUpdate();
	}

	/**
	 * Finds an alert given its name and owner.
	 *
	 * @param   em         The entity manager to use. Cannot be null.
	 * @param   alertName  The name of the alert. Cannot be null or empty.
	 * @param   owner      The owner of the alert. Cannot be null.
	 *
	 * @return  The corresponding alert or null if no alert having the specified name exists for the owner.
	 */
	public static Alert findByNameAndOwner(EntityManager em, String alertName, PrincipalUser owner) {
		requireArgument(em != null, "Entity manager can not be null.");
		requireArgument(alertName != null && !alertName.isEmpty(), "Alert name cannot be null or empty.");
		requireArgument(owner != null, "Owner cannot be null.");

		TypedQuery<Alert> query = em.createNamedQuery("Alert.findByNameAndOwner", Alert.class);
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		try {
			query.setParameter("name", alertName);
			query.setParameter("owner", owner);
			return query.getSingleResult();
		} catch (NoResultException ex) {
			return null;
		}
	}

	/**
	 * Finds all alerts for the given owner.
	 *
	 * @param   em     The entity manager to user. Cannot be null.
	 * @param   owner  The owner to retrieve alerts for. Cannot be null.
	 *
	 * @return  The list of alerts for the owner. Will never be null but may be empty.
	 */
	public static List<Alert> findByOwner(EntityManager em, PrincipalUser owner) {
		requireArgument(em != null, "Entity manager can not be null.");
		requireArgument(owner != null, "Owner cannot be null.");

		TypedQuery<Alert> query = em.createNamedQuery("Alert.findByOwner", Alert.class);
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		try {
			query.setParameter("owner", owner);
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Count the number of alerts for the given owner.
	 *
	 * @param em
	 *            The entity manager to user. Cannot be null.
	 * @param owner
	 *            owner The owner to retrieve alerts for. Cannot be null.
	 * @param searchText
	 * 			  The text to filter the search results.
	 *
	 * @return The total number of alerts for the owner.
	 */
	public static int countByOwner(EntityManager em, PrincipalUser owner, String searchText) {
		requireArgument(em != null, "Entity manager can not be null.");
		requireArgument(owner != null, "Owner cannot be null.");

		if (searchText != null) {
			searchText.trim();
		}

		try {
			TypedQuery<Long> query = null;

			if (searchText == null || searchText.isEmpty()) {
				query = em.createNamedQuery("Alert.countByOwner", Long.class);
			} else {
				query = em.createNamedQuery("Alert.countByOwnerWithSearchText", Long.class);
				query.setParameter(SEARCHTEXT_KEY, _convertSearchTextWildCardForQuery(searchText));
			}

			query.setHint(QueryHints.REFRESH, HintValues.TRUE);
			query.setHint("javax.persistence.cache.storeMode", "REFRESH");
			query.setParameter(OWNER_KEY, owner);

			return query.getSingleResult().intValue();
		} catch (NoResultException ex) {
			return 0;
		}
	}

	/**
	 * Find alerts meta filtered by the owner.
	 *
	 * @param em
	 *            The entity manager to user. Cannot be null.
	 * @param owner
	 *            The owner to retrieve alerts for. Cannot be null.
	 * @return A list of alerts owned by the owner.
	 */
	public static List<Alert> findByOwnerMeta(EntityManager em, PrincipalUser owner) {
		requireArgument(em != null, "Entity manager can not be null.");
		requireArgument(owner != null, "Owner can not be null.");

		try {
			Map<String, Object> whereParams = new HashMap<>();
			whereParams.put(DELETED_KEY, false);
			whereParams.put(OWNER_KEY, owner);

			// Get alerts meta
			return getAlertsMetaPaged(em, null, null, whereParams, null, null, null);
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Finds all alerts' meta for the given owner with given limit and offset.
	 *
	 * @param em
	 *            The entity manager to user. Cannot be null.
	 * @param owner
	 *            The owner to retrieve alerts for. Cannot be null.
	 * @param limit
	 *            The limit of return to return.
	 * @param offset
	 *            The starting offset of the result.
	 * @param searchText
	 * 			  The text to filter the search results.
	 * @param sortField
	 * 				The field of the alert that is used for sorting.
	 * @param sortOrder
	 * 				The order for sorting.
	 *
	 * @return The list of alerts for the owner.
	 */
	public static List<Alert> findByOwnerMetaPaged(EntityManager em, PrincipalUser owner, Integer limit,
			Integer offset, String searchText, String sortField, String sortOrder) {
		requireArgument(em != null, "Entity manager can not be null.");
		requireArgument(owner != null, "Owner cannot be null");

		if (searchText != null) {
			searchText.trim();
		}

		if (limit == null || limit <= 0) {
			limit = DEFAULT_PAGE_LIMIT;
		}
		if (offset == null || offset < 0) {
			offset = DEFAULT_PAGE_OFFSET;
		}

		try {
			Map<String, Object> whereParams = new HashMap<>();
			whereParams.put(DELETED_KEY, false);
			whereParams.put(OWNER_KEY, owner);

			// Get alerts meta
			return getAlertsMetaPaged(em, limit, offset, whereParams, searchText, sortField, sortOrder);
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Finds all alerts.
	 *
	 * @param   em  The entity manager to user. Cannot be null.
	 *
	 * @return  The list of all alerts. Will never be null but may be empty.
	 */
	public static List<Alert> findAll(EntityManager em) {
		requireArgument(em != null, "Entity manager can not be null.");

		TypedQuery<Alert> query = em.createNamedQuery("Alert.findAll", Alert.class);
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		try {
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Finds all alerts.
	 *
	 * @param   em  The entity manager to user. Cannot be null.
	 *
	 * @return  The list of all alerts. Will never be null but may be empty.
	 */
	public static List<Alert> findAllMeta(EntityManager em) {
		requireArgument(em != null, "Entity manager can not be null.");

		try {
			Map<String, Object> whereParams = new HashMap<>();
			whereParams.put(DELETED_KEY, false);

			// Get alerts meta
			return getAlertsMetaPaged(em, null, null, whereParams, null, null, null);
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Finds alerts by status (enabled/disabled).
	 *
	 * @param   em       The entity manager to user. Cannot be null.
	 * @param   enabled  Alert status (true for enabled jobs and false for disabled jobs).
	 *
	 * @return  The list of alerts for the given status. Will never be null but may be empty.
	 */
	public static List<Alert> findByStatus(EntityManager em, boolean enabled) {
		requireArgument(em != null, "Entity manager can not be null.");

		TypedQuery<Alert> query = em.createNamedQuery("Alert.findByStatus", Alert.class);

		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		query.setHint("eclipselink.join-fetch", "a.triggers");
		query.setHint("eclipselink.join-fetch", "a.notifications");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.triggers");
		query.setHint("eclipselink.left-join-fetch", "a.triggers.notifications");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.metricsToAnnotate");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.subscriptions");
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);

		try {
			query.setParameter("enabled", enabled);
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	public static List<Alert> findByRangeAndStatus(EntityManager em, BigInteger fromId, BigInteger toId, boolean enabled) {
		requireArgument(em != null, "Entity manager cannot be null.");
		requireArgument(fromId != null, "fromId cannot be null.");
		requireArgument(toId != null, "toId cannot be null.");

		TypedQuery<Alert> query = em.createNamedQuery("Alert.findByRangeAndStatus", Alert.class);

		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		query.setHint("eclipselink.join-fetch", "a.triggers");
		query.setHint("eclipselink.join-fetch", "a.notifications");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.triggers");
		query.setHint("eclipselink.left-join-fetch", "a.triggers.notifications");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.metricsToAnnotate");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.subscriptions");
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);

		try {
			query.setParameter("fromId", fromId);
			query.setParameter("toId", toId);
			query.setParameter("enabled", enabled);
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	public static List<Alert> findAlertsModifiedAfterDate(EntityManager em, Date modifiedDate) {
		requireArgument(em != null, "Entity manager cannot be null.");
		requireArgument(modifiedDate != null, "modifiedDate cannot be null.");

		TypedQuery<Alert> query = em.createNamedQuery("Alert.findAlertsModifiedAfterDate", Alert.class);

		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		query.setHint("eclipselink.join-fetch", "a.triggers");
		query.setHint("eclipselink.join-fetch", "a.notifications");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.triggers");
		query.setHint("eclipselink.left-join-fetch", "a.triggers.notifications");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.metricsToAnnotate");
		query.setHint("eclipselink.left-join-fetch", "a.notifications.subscriptions");
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);

		try {
			query.setParameter("modifiedDate",modifiedDate,TemporalType.TIMESTAMP);
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Finds alert ids by status (enabled/disabled).
	 *
	 * @param   em       The entity manager to user. Cannot be null.
	 * @param   enabled  Alert status (true for enabled jobs and false for disabled jobs).
	 *
	 * @return  The list of alert ids for the given status. Will never be null but may be empty.
	 */
	public static List<BigInteger> findIDsByStatus(EntityManager em, boolean enabled) {
		requireArgument(em != null, "Entity manager can not be null.");

		TypedQuery<BigInteger> query = em.createNamedQuery("Alert.findIDsByStatus", BigInteger.class);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		try {
			query.setParameter("enabled", enabled);
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Finds alert count by status (enabled/disabled).
	 *
	 * @param   em       The entity manager to user. Cannot be null.
	 * @param   enabled  Alert status (true for enabled jobs and false for disabled jobs).
	 *
	 * @return   alert count by status
	 */
	public static int alertCountByStatus(EntityManager em, boolean enabled) {
		requireArgument(em != null, "Entity manager can not be null.");

		TypedQuery<Long> query = em.createNamedQuery("Alert.countByStatus", Long.class);
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		try {
			query.setParameter("enabled", enabled);
			return query.getSingleResult().intValue();
		} catch (NoResultException ex) {
			return 0;
		}
	}

	/**
	 * Finds alerts by status (enabled/disabled).
	 *
	 * @param   em       The entity manager to user. Cannot be null.
	 * @param limit      The results limit
	 * @param offset     The results offset
	 * @param   enabled  Alert status (true for enabled jobs and false for disabled jobs).
	 *
	 * @return  The list of alerts for the given status. Will never be null but may be empty.
	 */
	public static List<Alert> findByLimitOffsetStatus(EntityManager em, int limit, int offset, boolean enabled) {
		requireArgument(em != null, "Entity manager can not be null.");

		TypedQuery<Alert> query = em.createNamedQuery("Alert.findByStatus", Alert.class);
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		try {
			query.setParameter("enabled", enabled);
			query.setFirstResult(offset);
			query.setMaxResults(limit);
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Finds all shared alerts with filtering.
	 *
	 * @param   em     The entity manager to user. Cannot be null.
	 * @param   owner  The owner of shared alerts to filter on
	 * @param   limit  The maximum number of rows to return.
	 *
	 * @return  The list of all shared alerts. Will never be null but may be empty.
	 */
	public static List<Alert> findSharedAlerts(EntityManager em, PrincipalUser owner, Integer limit) {
		requireArgument(em != null, "Entity manager can not be null.");

		TypedQuery<Alert> query;
		if(owner == null){
			query = em.createNamedQuery("Alert.getSharedAlerts", Alert.class);
		} else {
			query = em.createNamedQuery("Alert.getSharedAlertsByOwner", Alert.class);
			query.setParameter("owner", owner);
		}
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");

		if(limit!= null){
			query.setMaxResults(limit);
		}

		try {
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Count the total number of all shared alerts.
	 *
	 * @param em
	 *            The entity manager to user. Cannot be null.
	 * @param searchText
	 * 			  The text to filter the search results.
	 *
	 * @return The count of all shared alerts.
	 */
	public static int countSharedAlerts(EntityManager em, String searchText) {
		requireArgument(em != null, "Entity manager can not be null.");

		if (searchText != null) {
			searchText.trim();
		}

		try {
			TypedQuery<Long> query = null;

			if (searchText == null || searchText.isEmpty()) {
				query = em.createNamedQuery("Alert.countSharedAlerts", Long.class);
			} else {
				query = em.createNamedQuery("Alert.countSharedAlertsWithSearchText", Long.class);
				query.setParameter(SEARCHTEXT_KEY, _convertSearchTextWildCardForQuery(searchText));
			}

			query.setHint(QueryHints.REFRESH, HintValues.TRUE);
			query.setHint("javax.persistence.cache.storeMode", "REFRESH");

			return query.getSingleResult().intValue();
		} catch (NoResultException ex) {
			return 0;
		}
	}

	/**
	 * Gets all meta information of shared alerts with filtering.
	 *
	 * @param   em     The entity manager to user. Cannot be null.
	 * @param   owner  The owner to filter on
	 * @param   limit  The maximum number of rows to return.
	 *
	 * @return  The list of all shared alerts with meta information only. Will never be null but may be empty.
	 */
	public static List<Alert> findSharedAlertsMeta(EntityManager em, PrincipalUser owner, Integer limit) {
		requireArgument(em != null, "Entity manager can not be null.");

		try {
			Map<String, Object> whereParams = new HashMap<>();
			whereParams.put(DELETED_KEY, false);
			whereParams.put(SHARED_KEY, true);

			if (owner != null) {
				whereParams.put(OWNER_KEY, owner);
			}

			// Get alerts meta
			return getAlertsMetaPaged(em, limit, null, whereParams, null, null, null);
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Find all shared alerts meta with given limit and offset.
	 *
	 * @param em
	 *            The entity manager to user. Cannot be null.
	 * @param limit
	 *            The maximum number of rows to return.
	 * @param offset
	 *            The starting offset of the result.
	 * @param searchText
	 * 			  The text to filter the search results.
	 *  @param sortField
	 * 				The field of the alert that is used for sorting.
	 * @param sortOrder
	 * 				The order for sorting.
	 *
	 * @return The list of shared alerts with given limit and offset.
	 */
	public static List<Alert> findSharedAlertsMetaPaged(EntityManager em, Integer limit, Integer offset, String searchText,
		String sortField, String sortOrder) {
		requireArgument(em != null, "Entity manager can not be null.");

		if (searchText != null) {
			searchText.trim();
		}

		if (limit == null || limit <= 0) {
			limit = DEFAULT_PAGE_LIMIT;
		}
		if (offset == null || offset < 0) {
			offset = DEFAULT_PAGE_OFFSET;
		}

		try {
			// Get shared alerts
			Map<String, Object> whereParams = new HashMap<>();
			whereParams.put(DELETED_KEY, false);
			whereParams.put(SHARED_KEY, true);

			// Get alerts meta
			return getAlertsMetaPaged(em, limit, offset, whereParams, searchText, sortField, sortOrder);
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Find all private alerts (non-shared alerts) meta for given privileged user with given limit and offset.
	 *
	 * @param   em     The entity manager to user. Cannot be null.
	 * @param   owner  The owner to filter on
	 * @param   limit  The maximum number of rows to return.
	 * @param 	offset The starting offset of the result.
	 * @param searchText
	 * 			  The text to filter the search results.
	 * @param sortField
	 * 				The field of the alert that is used for sorting.
	 * @param sortOrder
	 * 				The order for sorting.
	 *
	 * @return The list of private alerts' meta with given limit and offset.
	 */
	public static List<Alert> findPrivateAlertsForPrivilegedUserMetaPaged(EntityManager em, PrincipalUser owner, Integer limit, Integer offset, String searchText,
		String sortField, String sortOrder) {
		requireArgument(em != null, "Entity manager can not be null.");

		if (searchText != null) {
			searchText.trim();
		}

		if (limit == null || limit <= 0) {
			limit = DEFAULT_PAGE_LIMIT;
		}
		if (offset == null || offset < 0) {
			offset = DEFAULT_PAGE_OFFSET;
		}

		// Invalid user nor non-privileged user shall not view other's non-shared alerts, thus immediately return empty list
		if (owner == null || !owner.isPrivileged()) {
			return new ArrayList<>(0);
		}

		try {
			// Query for alerts that are not marked as deleted, non-shared, owned by others
			Map<String, Object> whereParams = new HashMap<>();
			whereParams.put(DELETED_KEY, false);
			whereParams.put(SHARED_KEY, false);

			// Get alerts meta
			return getAlertsMetaPaged(em, limit, offset, whereParams, searchText, sortField, sortOrder);
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	/**
	 * Count the total number of private alerts (non-shared alerts) for
	 * privileged user.
	 *
	 * @param em
	 *            The entity manager to user. Cannot be null.
	 * @param owner
	 *            The owner to filter on.
	 * @param searchText
	 * 			  The text to filter the search results.
	 *
	 * @return The total number of private alerts for privileged user.
	 */
	public static int countPrivateAlertsForPrivilegedUser(EntityManager em, PrincipalUser owner, String searchText) {
		requireArgument(em != null, "Entity manager can not be null.");
		requireArgument(owner != null, "Owner cannot be null.");

		if (searchText != null) {
			searchText.trim();
		}

		if (!owner.isPrivileged()) {
			return 0;
		}

		try {
			TypedQuery<Long> query = null;

			if (searchText == null || searchText.isEmpty()) {
				query = em.createNamedQuery("Alert.countPrivateAlertsForPrivilegedUser", Long.class);
			} else {
				query = em.createNamedQuery("Alert.countPrivateAlertsForPrivilegedUserWithSearchText", Long.class);
				query.setParameter(SEARCHTEXT_KEY, _convertSearchTextWildCardForQuery(searchText));
			}

			query.setHint(QueryHints.REFRESH, HintValues.TRUE);
			query.setHint("javax.persistence.cache.storeMode", "REFRESH");

			return query.getSingleResult().intValue();
		} catch (NoResultException ex) {
			return 0;
		}
	}

	/**
	 * Finds all alerts whose name starts with the given prefix.
	 *
	 * @param   em      The entity manager to use. Cannot be null.
	 * @param   prefix  The name prefix to match. Cannot be null or empty.
	 *
	 * @return  The list of matching alerts. Will never be null, but may be empty.
	 */
	public static List<Alert> findByPrefix(EntityManager em, String prefix) {
		requireArgument(em != null, "Entity Manager cannot be null");
		requireArgument(prefix != null && !prefix.isEmpty(), "Cannot find alerts starting with null of empty prefix");

		TypedQuery<Alert> query = em.createNamedQuery("Alert.findByPrefix", Alert.class);
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		try {
			query.setParameter("name", prefix + "%");
			return query.getResultList();
		} catch (NoResultException ex) {
			return new ArrayList<>(0);
		}
	}

	//~ Methods **************************************************************************************************************************************

	/*
	 * A helper method executes the criteria query to get alerts meta with given
	 * limit and offset.
	 */
	private static List<Alert> getAlertsMetaPaged(EntityManager em, Integer limit, Integer offset,
			Map<String, Object> whereParams, String searchText, String sortField, String sortOrder) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Tuple> cq = cb.createTupleQuery();
		Root<Alert> e = cq.from(Alert.class);

		// Set fields to select
		List<Selection<?>> fieldsToSelect = new ArrayList<>();
		for (Field field : FieldUtils.getFieldsListWithAnnotation(Alert.class, Metadata.class)) {
			fieldsToSelect.add(e.get(field.getName()).alias(field.getName()));
		}
		cq.multiselect(fieldsToSelect);

		List<Predicate> predicates = new ArrayList<>();

		// Set WHERE conditions, so far we only use boolean and PrincipalUser
		// type conditions. New types can be easily added here on demand.
		if (whereParams != null && whereParams.size() > 0) {
			for (String key : whereParams.keySet()) {
				Object value = whereParams.get(key);
				if (value instanceof Boolean) {
					// Boolean type condition
					boolean val = (boolean) value;
					predicates.add(cb.equal(e.get(key), val));
				} else if (value instanceof PrincipalUser) {
					// PrincipalUser type condition
					predicates.add(cb.equal(e.get(key), (PrincipalUser) value));
				}
			}
		}

		// Filter on alert name and owner name if not empty. All values are
		// normalized to lower case for case insensitive search.
		if (searchText != null && !searchText.isEmpty()) {
			String searchPattern = _convertSearchTextWildCardForQuery(searchText);
			Expression<String> alertName = e.get("name");
			Expression<String> ownerName = e.join("owner").get("userName");
			predicates.add(cb.or(cb.like(cb.function("LOWER", String.class, alertName), searchPattern),
					cb.like(cb.function("LOWER", String.class, ownerName), searchPattern)));
		}

		if (predicates.size() > 0) {
			cq.where(predicates.toArray(new Predicate[predicates.size()]));
		}

		// By default, do not sort
		// Sort based or sortField and sortOrder if both are not null
		if (sortField != null && sortOrder != null){
			Expression<String> sortColumn;

			switch(SortFieldType.fromName(sortField)) {
				case OWNER_NAME :
					sortColumn = e.join("owner").get("userName");
					break;
				default :
					sortColumn = e.get(sortField);
					break;
			}

			switch(SortOrderType.fromName(sortOrder)){
				case ASC :
					cq.orderBy(cb.asc(sortColumn));
					break;
				case DESC :
					cq.orderBy(cb.desc(sortColumn));
					break;
				default :
					break;
			}
		}

		TypedQuery<Tuple> query = em.createQuery(cq);
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");
		query.setHint(QueryHints.REFRESH, HintValues.TRUE);

		// Set limit for pagination
		if (limit != null && limit > 0) {
			query.setMaxResults(limit);
		}

		// Set offset for pagination
		if (offset != null && offset >= 0) {
			query.setFirstResult(offset);
		}

		List<Tuple> result = query.getResultList();
		List<Alert> alerts = new ArrayList<>();

		for (Tuple tuple : result) {
			try {
				Alert a = new Alert(PrincipalUser.class.cast(tuple.get("createdBy")),
						PrincipalUser.class.cast(tuple.get("owner")), String.class.cast(tuple.get("name")),
						String.class.cast(tuple.get("expression")), String.class.cast(tuple.get("cronEntry")));

				a.id = BigInteger.class.cast(tuple.get("id"));
				a.enabled = Boolean.class.cast(tuple.get("enabled"));
				a.createdDate = Date.class.cast(tuple.get("createdDate"));
				a.modifiedDate = Date.class.cast(tuple.get("modifiedDate"));
				a.shared = Boolean.class.cast(tuple.get("shared"));
				a.modifiedBy = PrincipalUser.class.cast(tuple.get("modifiedBy"));
				a.missingDataNotificationEnabled = Boolean.class.cast(tuple.get("missingDataNotificationEnabled"));

				alerts.add(a);
			} catch (RuntimeException r) {
				// TODO: Add logging?
				continue;
			}
		}

		// Trim excessive items more then limit in the end
		if (limit != null && limit > 0) {
			alerts = alerts.subList(0, Math.min(alerts.size(), limit));
		}

		return alerts;
	}

	private static String _convertSearchTextWildCardForQuery(String searchText) {
		return "%" + searchText.toLowerCase().replace("*", "%").replace("?","_") + "%";
	}

	/**
	 * Returns the CRON entry for the alert.
	 *
	 * @return  The CRON entry for the alert.
	 */
	@Override
	public String getCronEntry() {
		return cronEntry;
	}

	/**
	 * Sets the CRON entry for the alert.
	 *
	 * @param  cronEntry  The new CRON entry. Cannot be null and must be valid CRON entry syntax.
	 */
	public void setCronEntry(String cronEntry) {
		requireArgument(cronEntry != null && !cronEntry.isEmpty(), "CronEntry cannot be null or empty.");
		this.cronEntry = cronEntry;
	}

	/**
	 * Returns the owner of the alert.
	 *
	 * @return  The alert owner.
	 */
	public PrincipalUser getOwner() {
		return owner;
	}

	/**
	 * Sets the owner of the alert.
	 *
	 * @param  owner  The alert owner. Cannot be null.
	 */
	public void setOwner(PrincipalUser owner) {
		requireArgument(owner != null, "Owner cannot be null.");
		this.owner = owner;
	}

	/**
	 * Returns the name of the alert.
	 *
	 * @return  The alert name.
	 */
	public String getName() {
		return name;
	}

	/**
	 * Sets the name of the alert.
	 *
	 * @param  name  The alert name. Cannot be null or empty.
	 */
	public void setName(String name) {
		requireArgument(name != null && !name.isEmpty(), "Name cannot be null or empty.");
		this.name = name;
	}

	/**
	 * Sets the expression which triggers will evaluate against.
	 *
	 * @return  The alert expression.
	 */
	public String getExpression() {
		return expression;
	}

	/**
	 * Sets the expression against which triggers will evaluate.
	 *
	 * @param  expression  The alert expression. Cannot be null and must be valid metric expression syntax as defined in the <tt>MetricService</tt>
	 */
	public void setExpression(String expression) throws RuntimeException {
		requireArgument(expression != null && !expression.isEmpty(), "Expression cannot be null or empty.");
		this.expression = expression;
	}

	/**
	 * Indicates if the alert is enabled.
	 *
	 * @return  True if the alert is enabled.
	 */
	public boolean isEnabled() {
		return enabled;
	}

	/**
	 * Indicates whether or not the alert is enabled.
	 *
	 * @param  enabled  True if the alert is enabled.
	 */
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	/**
	 * Indicates if an alert should trigger if no data is available to evaluate.
	 *
	 * @return  True if the alert should trigger when no data is available.
	 */
	public boolean isMissingDataNotificationEnabled() {
		return missingDataNotificationEnabled;
	}

	/**
	 * Indicates whether or not an alert should trigger if no data is available to evaluate.
	 *
	 * @param  missingDataNotificationEnabled  True if the alert should trigger when no data is available.
	 */
	public void setMissingDataNotificationEnabled(boolean missingDataNotificationEnabled) {
		this.missingDataNotificationEnabled = missingDataNotificationEnabled;
	}

	/**
	 * Returns the list of triggers associated with the alert.
	 *
	 * @return  The alerts triggers. Will not be null, but may be empty.
	 */
	public List<Trigger> getTriggers() {
		return Collections.unmodifiableList(triggers);
	}

	/**
	 * Replaces the triggers for the alert.
	 *
	 * @param  triggers  The new set of triggers.
	 */
	public void setTriggers(List<Trigger> triggers) {
		this.triggers.clear();
		if (triggers != null && !triggers.isEmpty()) {
			this.triggers.addAll(triggers);
		}
	}

	/**
	 * Returns the list of notifications associated with the alert.
	 *
	 * @return  The alerts notifications. Will not be null, but may be empty.
	 */
	public List<Notification> getNotifications() {
		return Collections.unmodifiableList(notifications);
	}

	/**
	 * Replaces the list of notifications associated with the alert.
	 *
	 * @param  notifications  The new set of notifications.
	 */
	public void setNotifications(List<Notification> notifications) {
		this.notifications.clear();
		if (notifications != null && !notifications.isEmpty()) {
			this.notifications.addAll(notifications);
		}
	}

	/**
	 * Adds a notification to the list of notifications associated with the alert.
	 * @param notification	The notification to add.
	 */
	public void addNotification(Notification notification) {
		if(notification != null) {
			this.notifications.add(notification);
		}
	}

	/**
	 * Indicates if the alert is shared.
	 *
	 * @return  True if the alert is shared.
	 */

	public boolean isShared() {
		return shared;
	}

	/**
	 * Indicates whether or not the alert is shared.
	 *
	 * @param  shared  True if the alert is shared.
	 **/
	public void setShared(boolean shared) {
		this.shared = shared;
	}

	/**
	 * Validates all fields of an alert.
	 * @throws RuntimeException
	 */
	public void validateAlert() throws RuntimeException {
		requireArgumentP(this.expression, x -> MetricReader.validateExpression(x), "Invalid alert expression: " + this.expression, true);
		requireArgument(Cron.isCronEntryValid(this.cronEntry), "Invalid cron entry: " + this.cronEntry);
		requireArgument(this.owner != null, "Owner cannot be null.");
		requireArgument(this.name != null && !this.name.isEmpty(), "Name cannot be null or empty.");
	}

	/**
	 * Returns whether the alert is valid
	 */
	public boolean isValid() {
		try
		{
			this.validateAlert();
		}
		catch (RuntimeException e)
		{
			return false;
		}
		return true;
	}

	/**
	 * Returns null if the alert is valid or the error message if it is not.
	 */
	public String validationMessage() {
		try
		{
			this.validateAlert();
		}
		catch (RuntimeException e)
		{
			return e.getMessage();
		}
		return null;
	}

	@Override
	public int hashCode() {
		int hash = 5;

		hash = 31 * hash + Objects.hashCode(this.name);
		hash = 31 * hash + Objects.hashCode(this.owner);
		hash = 31 * hash + Objects.hashCode(this.cronEntry);
		hash = 31 * hash + Objects.hashCode(this.enabled);
		hash = 31 * hash + Objects.hashCode(this.expression);
		hash = 31 * hash + Objects.hashCode(this.missingDataNotificationEnabled);
		hash = 31 * hash + Objects.hashCode(this.shared);

		return hash;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}

		final Alert other = (Alert) obj;

		if (this.hashCode() != other.hashCode()) {
			return false;
		}

		if (!CommonUtils.listsAreEquivelent(this.getTriggers(), other.getTriggers())) {
			return false;
		}

		if (!CommonUtils.listsAreEquivelent(this.getNotifications(), other.getNotifications())) {
			return false;
		}

		return true;
	}

	@Override
	public String toString() {
		return "Alert{" + "name=" + name + ", expression=" + expression + ", cronEntry=" + cronEntry + ", enabled=" + enabled +
				", missingDataNotificationEnabled=" + missingDataNotificationEnabled + ", notifications=" + notifications + ", triggers=" + triggers +
				", owner=" + owner + ", shared=" + shared + '}';
	}

	public static class Serializer extends JsonSerializer<Alert> {

		@Override
		public void serialize(Alert alert, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {

			jgen.writeStartObject();

			jgen.writeStringField("id", alert.getId().toString());
			jgen.writeStringField("name", alert.getName());
			jgen.writeStringField("expression", alert.getExpression());
			jgen.writeStringField("cronEntry", alert.getCronEntry());
			jgen.writeBooleanField("enabled", alert.isEnabled());
			jgen.writeBooleanField("missingDataNotificationEnabled", alert.isMissingDataNotificationEnabled());
			jgen.writeObjectField("owner", alert.getOwner());
			if(alert.getModifiedDate() != null) {
				jgen.writeObjectField("modifiedDate", alert.getModifiedDate().getTime());
			}

			jgen.writeArrayFieldStart("triggers");
			for(Trigger trigger : alert.getTriggers()) {
				jgen.writeObject(trigger);
			}
			jgen.writeEndArray();

			jgen.writeArrayFieldStart("notifications");
			for(Notification notification : alert.getNotifications()) {
				jgen.writeObject(notification);
			}
			jgen.writeEndArray();

			jgen.writeEndObject();
		}
	}

	// NOTE - ian - TODO - create a separate deserializer for testing OR handle missing info here?
	public static class Deserializer extends JsonDeserializer<Alert> {

		@Override
		public Alert deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

			SimpleModule module = new SimpleModule();
			module.addDeserializer(Trigger.class, new Trigger.Deserializer());
			module.addDeserializer(Notification.class, new Notification.Deserializer());
			module.addDeserializer(PrincipalUser.class, new Alert.PrincipalUserDeserializer());

			ObjectMapper mapper = new ObjectMapper();
			mapper.registerModule(module);

			Alert alert = new Alert();
			JsonNode rootNode = jp.getCodec().readTree(jp);

			BigInteger id = new BigInteger(rootNode.get("id").asText());
			alert.id = id;

			String name = rootNode.get("name").asText();
			alert.setName(name);

			String expression = rootNode.get("expression").asText();

			alert.setExpression(expression);

			String cronEntry = rootNode.get("cronEntry").asText();
			alert.setCronEntry(cronEntry);

//			if(rootNode.get("modifiedDate") != null) {
//				alert.setModifiedDate(Date.from(Instant.ofEpochMilli(rootNode.get("modifiedDate").asLong())));
//			}

			boolean missingDataNotificationEnabled = rootNode.get("missingDataNotificationEnabled").asBoolean();
			alert.setMissingDataNotificationEnabled(missingDataNotificationEnabled);

			JsonNode onwerNode = rootNode.get("owner");
			PrincipalUser owner = mapper.treeToValue(onwerNode, PrincipalUser.class);
			alert.setOwner(owner);

			List<Trigger> triggers = new ArrayList<>();
			JsonNode triggersArrayNode = rootNode.get("triggers");
			if(triggersArrayNode.isArray()) {
				for(JsonNode triggerNode : triggersArrayNode) {
					Trigger trigger = mapper.treeToValue(triggerNode, Trigger.class);
					trigger.setAlert(alert);
					triggers.add(trigger);
				}
			}
			alert.setTriggers(triggers);

			List<Notification> notifications = new ArrayList<>();
			JsonNode notificationsArrayNode = rootNode.get("notifications");
			if(notificationsArrayNode.isArray()) {
				for(JsonNode notificationNode : notificationsArrayNode) {
					Notification notification  = mapper.treeToValue(notificationNode, Notification.class);
					notification.setAlert(alert);
					_replaceTriggerObjectsContainingOnlyIDsWithActualObjects(notification, notification.getTriggers(), triggers);
					notifications.add(notification);
				}
			}
			alert.setNotifications(notifications);

			// This needs to be last because alerts won't validate unless they are complete.
			boolean enabled = rootNode.get("enabled").asBoolean();
			alert.setEnabled(enabled);

			return alert;
		}

		private void _replaceTriggerObjectsContainingOnlyIDsWithActualObjects(Notification notification, List<Trigger> triggersWithIDsOnly,
				List<Trigger> triggers) {

			List<Trigger> triggersToAdd = new ArrayList<>(triggersWithIDsOnly.size());
			for(Trigger trigger : triggers) {
				if(_contains(trigger.getId(), triggersWithIDsOnly)) {
					triggersToAdd.add(trigger);
				}
			}

			notification.setTriggers(triggersToAdd);

		}

		private boolean _contains(BigInteger triggerID, List<Trigger> triggersWithIDsOnly) {

			for(Trigger trigger : triggersWithIDsOnly) {
				if(trigger.getId().equals(triggerID)) {
					return true;
				}
			}

			return false;
		}

	}

	public static class PrincipalUserSerializer extends JsonSerializer<PrincipalUser> {

		@Override
		public void serialize(PrincipalUser value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
			jgen.writeStartObject();
			jgen.writeStringField("id", value.getId().toString());
			jgen.writeStringField("username", value.getUserName());
			jgen.writeStringField("email", value.getEmail());
			jgen.writeEndObject();
		}
	}

	public static class PrincipalUserDeserializer extends JsonDeserializer<PrincipalUser> {

		@Override
		public PrincipalUser deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

			PrincipalUser user = new PrincipalUser();
			JsonNode rootNode = jp.getCodec().readTree(jp);

			BigInteger id = new BigInteger(rootNode.get("id").asText());
			user.id = id;

			String username = rootNode.get("username").asText();
			user.setUserName(username);

			String email = rootNode.get("email").asText();
			user.setEmail(email);

			return user;
		}
	}

		//~ Enums **************************************************************************************************************************************
		public enum SortFieldType {

			OWNER_NAME("ownerName"),
			NAME("name"),
			MODIFIED_DATE("modifiedDate"),
			CREATED_DATE("createdDate");

			private String name_;
			private SortFieldType(String name){
				name_ = name;
			}

			/**
			 * Returns a given sort field type corresponding to the given name.
			 *
			 * @param name  The sort field type name
			 *
			 * @return			The sort field type
			 */
			public static SortFieldType fromName(String name) {
				for (SortFieldType t: SortFieldType.values()) {
					if (t.getName().equalsIgnoreCase(name)) {
						return t;
					}
				}
				String errorMessage = "SortFieldType " + name
					+ " does not exist or is not supported. Allowed values are: "
					+ Arrays.asList(SortFieldType.values()).stream().map(t -> t.getName()).collect(Collectors.toList());

				LOGGER.error(errorMessage + "\n");
				throw new IllegalArgumentException(errorMessage);
			}

			/**
			 * Return sort field type name.
			 *
			 * @return	The sort field type name\
			 *
			 */
			public String getName(){
				return name_;
			}
		}

		public enum SortOrderType {

			ASC,
			DESC;

			/**
			 * Returns a given sort order type corresponding to the given name.
			 *
			 * @param name 	The sort order type name
			 *
			 * @return      The sort order type
			 */
			public static SortOrderType fromName(String name) {
				for (SortOrderType t : SortOrderType.values()) {
					if (t.getName().equalsIgnoreCase(name)) {
						return t;
					}
				}
				String errorMessage = "SortOrderType " + name
					+ " does not exist or is not supported. Allowed values are: "
					+ Arrays.asList(SortOrderType.values());

				LOGGER.error(errorMessage + "\n");
				throw new IllegalArgumentException(errorMessage);
			}

			/**
			 * Return Sort order type name.
			 *
			 * @return	The sort order type name
			 *
			 */
			public String getName(){
				return this.toString();
			}
		}

}
/* Copyright (c) 2016, Salesforce.com, Inc.  All rights reserved. */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.jboss.shrinkwrap.descriptor.api.ejbjar31
</TITLE>

<META NAME="date" CONTENT="2011-07-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

org.jboss.shrinkwrap.descriptor.api.ejbjar31

Interfaces

AccessTimeoutType

ActivationConfigPropertyType

ActivationConfigType

ApplicationExceptionType

AroundInvokeType

AroundTimeoutType

AssemblyDescriptorType

AsyncMethodType

CmpFieldType

CmrFieldType

ConcurrentMethodType

ContainerTransactionType

DependsOnType

EjbJar31Descriptor

EjbJarType

EjbRelationshipRoleType

EjbRelationType

EnterpriseBeansType

EntityBeanType

ExcludeListType

InitMethodType

InterceptorBindingType

InterceptorOrderType

InterceptorsType

InterceptorType

MessageDrivenBeanType

MethodParamsType

MethodPermissionType

MethodType

NamedMethodType

QueryMethodType

QueryType

RelationshipRoleSourceType

RelationshipsType

RemoveMethodType

SecurityIdentityType

SessionBeanType

StatefulTimeoutType

TimerScheduleType

TimerType

Enums

CmpVersionType

CmrFieldTypeType

ConcurrencyManagementTypeType

ConcurrentLockTypeType

MethodIntfType

MultiplicityType

PersistenceTypeType

ResultTypeMappingType

SessionTypeType

TimeUnitTypeType

TransactionTypeType

TransAttributeType


text:
'use strict';

(function() {
	// Parcials Controller Spec
	describe('Parcials Controller Tests', function() {
		// Initialize global variables
		var ParcialsController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the Parcials controller.
			ParcialsController = $controller('ParcialsController', {
				$scope: scope
			});
		}));

		it('$scope.find() should create an array with at least one Parcial object fetched from XHR', inject(function(Parcials) {
			// Create sample Parcial using the Parcials service
			var sampleParcial = new Parcials({
				name: 'New Parcial'
			});

			// Create a sample Parcials array that includes the new Parcial
			var sampleParcials = [sampleParcial];

			// Set GET response
			$httpBackend.expectGET('parcials').respond(sampleParcials);

			// Run controller functionality
			scope.find();
			$httpBackend.flush();

			// Test scope value
			expect(scope.parcials).toEqualData(sampleParcials);
		}));

		it('$scope.findOne() should create an array with one Parcial object fetched from XHR using a parcialId URL parameter', inject(function(Parcials) {
			// Define a sample Parcial object
			var sampleParcial = new Parcials({
				name: 'New Parcial'
			});

			// Set the URL parameter
			$stateParams.parcialId = '525a8422f6d0f87f0e407a33';

			// Set GET response
			$httpBackend.expectGET(/parcials\/([0-9a-fA-F]{24})$/).respond(sampleParcial);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.parcial).toEqualData(sampleParcial);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Parcials) {
			// Create a sample Parcial object
			var sampleParcialPostData = new Parcials({
				name: 'New Parcial'
			});

			// Create a sample Parcial response
			var sampleParcialResponse = new Parcials({
				_id: '525cf20451979dea2c000001',
				name: 'New Parcial'
			});

			// Fixture mock form input values
			scope.name = 'New Parcial';

			// Set POST response
			$httpBackend.expectPOST('parcials', sampleParcialPostData).respond(sampleParcialResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.name).toEqual('');

			// Test URL redirection after the Parcial was created
			expect($location.path()).toBe('/parcials/' + sampleParcialResponse._id);
		}));

		it('$scope.update() should update a valid Parcial', inject(function(Parcials) {
			// Define a sample Parcial put data
			var sampleParcialPutData = new Parcials({
				_id: '525cf20451979dea2c000001',
				name: 'New Parcial'
			});

			// Mock Parcial in scope
			scope.parcial = sampleParcialPutData;

			// Set PUT response
			$httpBackend.expectPUT(/parcials\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/parcials/' + sampleParcialPutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid parcialId and remove the Parcial from the scope', inject(function(Parcials) {
			// Create new Parcial object
			var sampleParcial = new Parcials({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new Parcials array and include the Parcial
			scope.parcials = [sampleParcial];

			// Set expected DELETE response
			$httpBackend.expectDELETE(/parcials\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleParcial);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.parcials.length).toBe(0);
		}));
	});
}());