text:
package test;

import static org.junit.Assert.*;

import java.util.Date;

import org.junit.Test;

import core.runtime.confluence.ConfluenceClient;
import core.runtime.confluence.IConfluenceClient;
import core.runtime.confluence.IConfluenceClient.PageInfo;
import core.runtime.logger.ILogConfig;
import core.runtime.logger.Logger;
import core.runtime.logger.ILogConfig.Module;
import core.runtime.logger.Logger.Mode;

public class ConfluenceClientTest {

	private static final String CONFLUENCE_SERVER = "http://10.42.84.232:8080";
	private static final String CONFLUENCE_SPACE_KEY = "ds";
	private static final String CONFLUENCE_PAGE_TITLE = "Juggernaut-Test";
	private static final String CONFLUENCE_PAGE_ID = "21037090";

	private Logger logger;
	private ConfluenceClient client;

	public ConfluenceClientTest(){
		logger = new Logger(null, Mode.CONSOLE);
		logger.setConfig(new ILogConfig(){
			@Override
			public Level getLogLevel(Module module) {
				return Level.DEBUG;
			}
		});
		client = new ConfluenceClient();
	}

	@Test public void testGetInfo() {

		logger.info(Module.COMMON, "Confluence Info");
		try{
			client.login(CONFLUENCE_SERVER, IConfluenceClient.RPC_USER, IConfluenceClient.RPC_USER, logger);
			try{
				PageInfo pageInfo = client.getInfo(CONFLUENCE_SPACE_KEY, CONFLUENCE_PAGE_TITLE, logger);
				assertEquals(CONFLUENCE_PAGE_ID, pageInfo.pageId);
			}finally{
				client.logout(logger);
			}
		}catch(Exception e){
			logger.error(Module.COMMON, e);
			fail(e.getMessage());
		}
	}

	@Test public void testUpdatePage() {

		logger.info(Module.COMMON, "Confluence Update");
		try{
			client.login(CONFLUENCE_SERVER, IConfluenceClient.RPC_USER, IConfluenceClient.RPC_USER, logger);
			try{
				PageInfo pageInfo = client.getInfo(CONFLUENCE_SPACE_KEY, CONFLUENCE_PAGE_TITLE, logger);
				client.updatePage(pageInfo, ""+(new Date()).getTime(), logger);
			}finally{
				client.logout(logger);
			}
		}catch(Exception e){
			logger.error(Module.COMMON, e);
			fail(e.getMessage());
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="separator">#707070</color>

</resources>

redpajama_set_name: RedPajamaGithub


text:
package slick.migration.dialect

import slick.migration.ast._

class DB2Dialect(driver: DB2Driver) extends Dialect[DB2Driver](driver) {
  override def autoInc(ci: ColumnInfo) =
    if (ci.autoInc) " GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)" else ""

  /** It cannot be rename if there is any foreign keys and/or any othert table that is referncing on table to remove */
  override def renameTable(table: TableInfo, to: String) =
    s"RENAME TABLE ${quoteTableName(table)} TO ${quoteIdentifier(to)}"

  override def renameIndex(old: IndexInfo, newName: String): Seq[String] = List(
    s"RENAME INDEX ${quoteIdentifier(old.name)} TO ${quoteIdentifier(newName)}"
  )

  override def addColumn(table: TableInfo, column: ColumnInfo) = {
    s"ALTER TABLE ${quoteTableName(table)} ADD ${addColumnSql(column)}"
  }

  override def renameColumn(table: TableInfo, from: ColumnInfo, to: String) =
    s"""ALTER TABLE ${quoteTableName(table)}
      | RENAME COLUMN ${quoteIdentifier(from.name)}
      | TO ${quoteIdentifier(to)}""".stripMargin

  /**
   * If column is marked as "NOT NULL" and default is not provided then add such column as nullable,
   * otherwise add by default.
   */
  private def addColumnSql(ci: ColumnInfo): String = {
    def name = quoteIdentifier(ci.name)
    def typ = columnType(ci)
    def default = ci.default.map(" DEFAULT " + _).getOrElse("")

    if (ci.notNull && default.isEmpty)
      s"$name $typ NULL ${primaryKey(ci, false)}"
    else
      s"$name $typ$default${notNull(ci)}${primaryKey(ci, false)}"
  }
}


text:
extern "C"
{
#endif

widget_t* create_label(char* text);

#ifdef __cplusplus
}
#endif

#endif


text:
module ScRockPaperScissors
  class Player
    @@valid_answers = %w(r p s)
  end
end


text:
module Azure::ServiceFabric::V7_0_0_42
  module Models
    #
    # Describes a setting for the container. The setting file path can be
    # fetched from environment variable "Fabric_SettingPath". The path for
    # Windows container is "C:\\secrets". The path for Linux container is
    # "/var/secrets".
    #
    class Setting

      include MsRestAzure

      # @return [SettingType] The type of the setting being given in value.
      # Possible values include: 'ClearText', 'KeyVaultReference',
      # 'SecretValueReference'. Default value: 'ClearText' .
      attr_accessor :type

      # @return [String] The name of the setting.
      attr_accessor :name

      # @return [String] The value of the setting, will be processed based on
      # the type provided.
      attr_accessor :value

      #
      # Mapper for Setting class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'Setting',
          type: {
            name: 'Composite',
            class_name: 'Setting',
            model_properties: {
              type: {
                client_side_validation: true,
                required: false,
                serialized_name: 'type',
                default_value: 'ClearText',
                type: {
                  name: 'String'
                }
              },
              name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              value: {
                client_side_validation: true,
                required: false,
                serialized_name: 'value',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


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

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>SLF4J 1.7.26 Reference Package org.slf4j.migrator.internal</title>
		<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="style" />

        	org.slf4j.migrator.internal

Classes

            	NopProgressListener


text:
/*
 * Created on Mar 31, 2005
 */
package org.cobraparser.async;

import java.util.EventObject;

/**
 * An asynchronous result event. This is a generic class with a
 * TResult type parameter, the type of the result.
 *
 * @see org.cobraparser.async.AsyncResultListener
 * @author J. H. S.
 */
final class AsyncResultEvent<TResult> extends EventObject {
  private static final long serialVersionUID = -4837654436436995017L;
  private final TResult result;

  /**
   * Instance constructor.
   *
   * @param source
   *          The event source.
   * @param result
   *          The asynchronous result.
   */
  public AsyncResultEvent(final Object source, final TResult result) {
    super(source);
    this.result = result;
  }

  /**
   * Gets the asynchronous result. This may be an exception instance.
   */
  public TResult getResult() {
    return this.result;
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Arnold Arbor. 12:72. 1931 "<I>crenato-serrata</I>"

#### Original name
Photinia crenatoserrata Hance

### Remarks
null


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../openssl_sys/fn.EC_POINT_is_on_curve.html">

Redirecting to ../../openssl_sys/fn.EC_POINT_is_on_curve.html...


text:
<?php
class Garp_Service_Amazon_SesMock extends Garp_Service_Amazon_Ses {
    protected static $_requests = array();

    public function _makeRequest($args = array()) {
        static::$_requests[] = $args;
    }

    public function getRequest($n) {
        return isset(static::$_requests[$n]) ? static::$_requests[$n] : null;
    }

    public function getRequests() {
        return static::$_requests;
    }

    public static function clearRequests() {
        static::$_requests = array();
    }

}


text:
package xal.app.orbitcorrect;

import xal.smf.*;

import java.util.*;

/**
 * FlattenListener
 *
 * @author   tap
 * @since    Oct 06, 2004
 */
public interface FlattenListener {
	/**
	 * sequence changed
	 * @param source     Description of the Parameter
	 * @param simulator  the new simulator
	 */
	public void simulatorChanged( Flattener source, MachineSimulator simulator );

	/**
	 * solving time changed
	 * @param source       the flattener whose solving time changed
	 * @param solvingTime  new solving time in seconds
	 */
	public void solvingTimeChanged( Flattener source, double solvingTime );

	/**
	 * sequence changed
	 * @param source    Description of the Parameter
	 * @param sequence  the new sequence
	 */
	public void sequenceChanged( Flattener source, AcceleratorSeq sequence );

	/**
	 * BPMs changed
	 * @param source  Description of the Parameter
	 * @param bpmAgents    Description of the Parameter
	 */
	public void bpmsChanged( Flattener source, List<BpmAgent> bpmAgents );

	/**
	 * Correctors changed
	 * @param source      Description of the Parameter
	 * @param supplies  Description of the Parameter
	 */
	public void correctorSuppliesChanged( Flattener source, List<CorrectorSupply> supplies );

	/**
	 * New optimal orbit found
	 * @param source  Description of the Parameter
	 * @param orbit   Description of the Parameter
	 */
	public void newOptimalOrbit( Flattener source, Orbit orbit );

	/**
	 * indicates that the flattener progress has been updated
	 * @param source            Description of the Parameter
	 * @param fractionComplete  Description of the Parameter
	 * @param message           Description of the Parameter
	 */
	public void progressUpdated( Flattener source, double fractionComplete, String message );
}


text:
Capistrano::Configuration.instance.load do

  set_default(:sidekiq_pid) { "#{shared_path}/pids/sidekiq.pid" }
  set_default(:sidekiq_log) { "#{shared_path}/log/sidekiq.log" }

  namespace :sidekiq do

    task :setup, roles: :app do
      template("init.d/sidekiq.erb.sh", "/tmp/sidekiq")
      run "#{sudo} chmod +x /tmp/sidekiq"
      run "#{sudo} mv -u /tmp/sidekiq /etc/init.d/sidekiq"
      run "#{sudo} update-rc.d -f sidekiq defaults"
    end

    desc "Generate a 'default' sidekiq.yml configuration file."
    task :config, roles: :app do
      run "mkdir -p #{shared_path}/config"
      template "sidekiq.yml.erb", "#{shared_path}/config/sidekiq.yml"
    end

    desc "Symlink the database.yml file into latest release"
    task :symlink, roles: :app do
      run "ln -nfs #{shared_path}/config/sidekiq.yml #{release_path}/config/sidekiq.yml"
    end
    after "deploy:finalize_update", "sidekiq:symlink"

    desc "Clear Sidekiq Retry Queue"
    task :clear_queue, roles: :app do
      run "cd #{current_path} && bundle exec rake sidekiq:clear_queue RAILS_ENV=#{rails_env}"
    end

  end
end


text:
// Copyright 2011 Google Inc.
//
// 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.

package com.google.enterprise.connector.notes;

import com.google.common.annotations.VisibleForTesting;
import com.google.enterprise.connector.notes.client.NotesDatabase;
import com.google.enterprise.connector.notes.client.NotesDocument;
import com.google.enterprise.connector.notes.client.NotesDocumentCollection;
import com.google.enterprise.connector.notes.client.NotesEmbeddedObject;
import com.google.enterprise.connector.notes.client.NotesItem;
import com.google.enterprise.connector.notes.client.NotesRichTextItem;
import com.google.enterprise.connector.notes.client.NotesSession;
import com.google.enterprise.connector.notes.client.NotesView;
import com.google.enterprise.connector.spi.RepositoryException;
import com.google.enterprise.connector.spi.SpiConstants.ActionType;

import java.io.File;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class NotesCrawlerThread extends Thread {
  private static final String CLASS_NAME = NotesCrawlerThread.class.getName();
  private static final Logger LOGGER = Logger.getLogger(CLASS_NAME);
  static final String META_FIELDS_PREFIX = "x.";

  private final NotesConnector nc;
  private final NotesConnectorSession ncs;
  private NotesSession ns = null;
  private NotesDatabase cdb = null;
  @VisibleForTesting
  NotesDocument templateDoc = null;
  @VisibleForTesting
  NotesDocument formDoc = null;
  @VisibleForTesting
  NotesDocumentCollection formsdc = null;
  private String openDbRepId = "";
  private NotesDatabase srcdb = null;
  private NotesView crawlQueue = null;

  @VisibleForTesting
  List<MetaField> metaFields;

  NotesCrawlerThread(NotesConnector Connector, NotesConnectorSession Session) {
    final String METHOD = "NotesCrawlerThread";
    LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
        "NotesCrawlerThread being created.");

    nc = Connector;
    ncs = Session;
  }

  // Since we are multi-threaded, each thread has its own objects
  // which are not shared.  Hence the calling thread must pass
  // the Domino objects to this method.
  @VisibleForTesting
  static synchronized NotesDocument getNextFromCrawlQueue(
      NotesSession ns, NotesView crawlQueue) {
    final String METHOD = "getNextFromCrawlQueue";
    try {
      crawlQueue.refresh();
      NotesDocument nextDoc = crawlQueue.getFirstDocument();
      if (nextDoc == null) {
        return null;
      }
      LOGGER.logp(Level.FINER, CLASS_NAME, METHOD, "Prefetching document");
      nextDoc.replaceItemValue(NCCONST.NCITM_STATE, NCCONST.STATEINCRAWL);
      nextDoc.save(true);

      return nextDoc;
    } catch (Exception e) {
      LOGGER.log(Level.SEVERE, CLASS_NAME, e);
    } finally {
    }
    return null;
  }

  protected void loadTemplateDoc(String TemplateName)
      throws RepositoryException {
    final String METHOD = "loadTemplate";
    LOGGER.entering(CLASS_NAME, METHOD);

    // Is a template document all ready loaded?
    if (null != templateDoc) {
      // Is this the one we need?
      if (TemplateName.equals(
              templateDoc.getItemValueString(NCCONST.TITM_TEMPLATENAME))) {
        return;
      }
      templateDoc.recycle();
      templateDoc = null;
      if (null != formsdc) {
        formsdc.recycle();
      }
      formsdc = null;
      if (null != formDoc) {
        formDoc.recycle();
      }
      formDoc = null;
    }
    NotesView vw = cdb.getView(NCCONST.VIEWTEMPLATES);
    templateDoc = vw.getDocumentByKey(TemplateName, true);
    formsdc = templateDoc.getResponses();

    // Parse any configured MetaFields once per template load.
    Vector templateMetaFields =
        templateDoc.getItemValue(NCCONST.TITM_METAFIELDS);
    metaFields = new ArrayList<MetaField>(templateMetaFields.size());
    for (Object o : templateMetaFields) {
      metaFields.add(new MetaField((String) o));
    }
    if (LOGGER.isLoggable(Level.FINEST)) {
      LOGGER.finest("template MetaFields: '" + templateMetaFields
          + "'; parsed MetaFields: " + metaFields);
    }
    vw.recycle();
  }

  protected void loadForm(String FormName) throws RepositoryException {
    final String METHOD = "loadForm";
    LOGGER.entering(CLASS_NAME, METHOD);

    if (null != formDoc) {
      if (FormName == formDoc.getItemValueString(NCCONST.FITM_LASTALIAS)) {
        return;
      }
      formDoc.recycle();
      formDoc = null;
    }
    if (null == formsdc) {
      return;
    }
    formDoc = formsdc.getFirstDocument();
    while (null != formDoc) {
      String formDocName = formDoc.getItemValueString(NCCONST.FITM_LASTALIAS);
      if (formDocName.equals(FormName)) {
        return;
      }
      NotesDocument prevDoc = formDoc;
      formDoc = formsdc.getNextDocument(prevDoc);
      prevDoc.recycle();
    }
  }

  /*
   *   Some comments on Domino.
   *
   *   Reader security is only enforced in Domino if there are
   *   Readers fields on the document and they are non-blank
   *
   *   Authors fields also provide read access to the document if
   *   document level security is enforced.  However if there are
   *   authors fields, but not any non-blank readers fields,
   *   document level security will not be enforced.
   */
  protected void setDocumentReaderNames(NotesDocument crawlDoc,
      NotesDocument srcDoc) throws RepositoryException {
    final String METHOD = "setDocumentReaderNames";
    LOGGER.entering(CLASS_NAME, METHOD);

    Vector<?> allItems = srcDoc.getItems();
    try {
      Vector<String> authorReaders = new Vector<String>();
      boolean hasReaders = false;
      Vector<Integer> authorItems = new Vector<Integer>();

      // Find the Readers field(s), if any. There can be more
      // than one Readers field.
      for (int i = 0; i < allItems.size(); i++) {
        NotesItem item = (NotesItem) allItems.elementAt(i);
        if (item.isReaders()) {
          boolean hasCurrentItemReaders =
              copyValues(item, authorReaders, "readers");
          hasReaders = hasCurrentItemReaders || hasReaders;
        } else if (item.isAuthors()) {
          authorItems.add(i);
        }
      }
      // If there are Readers, add any Authors to the Readers list
      // for AuthZ purposes. With no Readers, database security applies.
      if (hasReaders && authorItems.size() > 0) {
        for (Integer i : authorItems) {
          copyValues((NotesItem) allItems.elementAt(i),
              authorReaders, "authors");
        }
      }

      LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
          "Document readers for "
          + crawlDoc.getItemValueString(NCCONST.ITM_DOCID)
          + " are " + authorReaders);
      if (authorReaders.size() > 0) {
        crawlDoc.replaceItemValue(NCCONST.NCITM_DOCAUTHORREADERS,
            authorReaders);
        crawlDoc.replaceItemValue(NCCONST.NCITM_DOCREADERS, authorReaders);
      }
    } finally {
      srcDoc.recycle(allItems);
    }
  }

  private boolean copyValues(NotesItem item, Vector<String> destination,
      String description) throws RepositoryException {
    final String METHOD = "copyValues";
    Vector values = item.getValues();
    int count = 0;
    if (null != values) {
      LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
          "Adding " + description + " " + values.toString());
      for (; count < values.size(); count++) {
        destination.add(values.elementAt(count).toString().toLowerCase());
      }
    }
    return count > 0;
  }

  // This function will set google security fields for the document
  protected void setDocumentSecurity(NotesDocument crawlDoc)
      throws RepositoryException {
    final String METHOD = "setDocumentSecurity";
    LOGGER.entering(CLASS_NAME, METHOD);

    String AuthType = crawlDoc.getItemValueString(NCCONST.NCITM_AUTHTYPE);

    crawlDoc.replaceItemValue(NCCONST.ITM_ISPUBLIC,
        String.valueOf(AuthType.equals(NCCONST.AUTH_NONE)));
  }

  protected void evaluateField(NotesDocument crawlDoc, NotesDocument srcDoc,
      String formula, String ItemName, String Default)
      throws RepositoryException {
    final String METHOD = "evaluateField";
    LOGGER.entering(CLASS_NAME, METHOD);

    Vector<?> VecEvalResult = null;
    String Result = null;
    try {
      LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
          "Evaluating formula for item " + ItemName + " : src is: " + formula);
      VecEvalResult = ns.evaluate(formula, srcDoc);
      // Make sure we dont' get an empty vector or an empty string
      if (VecEvalResult != null) {
        if (VecEvalResult.size() > 0) {
          Result = VecEvalResult.elementAt(0).toString();
          LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
              "Evaluating formula result is: " + Result);
        }
      }
      if (null == Result) {
        Result = Default;
      }
      if (Result.length() == 0) {
        Result = Default;
      }
    } catch (RepositoryException e) {
      LOGGER.log(Level.SEVERE, CLASS_NAME, e);
    } finally {
      crawlDoc.replaceItemValue(ItemName, Result);
    }
    LOGGER.exiting(CLASS_NAME, METHOD);
  }

  // TODO: Consider mapping other fields so they can be used for
  // dynamic navigation.  This could be an configurable option.

  // This function will map the fields from the source database
  // to the crawl doc using the configuration specified in
  // formDoc
  protected void mapFields(NotesDocument crawlDoc, NotesDocument srcDoc)
      throws RepositoryException {
    final String METHOD = "mapFields";
    LOGGER.entering(CLASS_NAME, METHOD);

    // Copy the standard fields
    String NotesURL = srcDoc.getNotesURL();
    String HttpURL = getHTTPURL(crawlDoc);
    crawlDoc.replaceItemValue(NCCONST.ITM_DOCID, HttpURL);
    crawlDoc.replaceItemValue(NCCONST.ITM_DISPLAYURL, HttpURL);
    crawlDoc.replaceItemValue(NCCONST.ITM_GMETAFORM,
        srcDoc.getItemValueString(NCCONST.ITMFORM));
    crawlDoc.replaceItemValue(NCCONST.ITM_LASTMODIFIED,
        srcDoc.getLastModified());
    crawlDoc.replaceItemValue(NCCONST.ITM_GMETAWRITERNAME, srcDoc.getAuthors());
    crawlDoc.replaceItemValue(NCCONST.ITM_GMETALASTUPDATE,
        srcDoc.getLastModified());
    crawlDoc.replaceItemValue(NCCONST.ITM_GMETACREATEDATE, srcDoc.getCreated());

    // We need to generate the title and description using a formula
    String formula = null;
    // When there is no form configuration use the config from the template
    if (formDoc != null) {
      formula = formDoc.getItemValueString(NCCONST.FITM_SEARCHRESULTSFORMULA);
    }
    else {
      formula = templateDoc.getItemValueString(NCCONST.TITM_SEARCHRESULTSFIELDS);
    }
    evaluateField(crawlDoc, srcDoc, formula, NCCONST.ITM_TITLE, "");

    // Again..when there is no form configuration use the config
    // from the template
    if (formDoc != null) {
      formula = formDoc.getItemValueString(NCCONST.FITM_DESCRIPTIONFORMULA);
    }
    else {
      formula = templateDoc.getItemValueString(NCCONST.TITM_DESCRIPTIONFIELDS);
    }
    evaluateField(crawlDoc, srcDoc, formula, NCCONST.ITM_GMETADESCRIPTION, "");
    LOGGER.exiting(CLASS_NAME, METHOD);

    // DO NOT MAP THIS FIELD - it will force the GSA to try and crawl this URL
    // crawlDoc.replaceItemValue(NCCONST.ITM_SEARCHURL, HttpURL);
  }

  @VisibleForTesting
  void mapMetaFields(NotesDocument crawlDoc, NotesDocument srcDoc)
      throws RepositoryException {
    final String METHOD = "mapMetaFields";
    LOGGER.entering(CLASS_NAME, METHOD);
    NotesItem item = null;
    for (MetaField mf : metaFields) {
      try {
        if (null == mf.getFieldName()) {
          if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
                "Skipping null fieldname");
          }
          continue;
        }
        String configForm = mf.getFormName();
        if (null != configForm) {
          String docForm = srcDoc.getItemValueString(NCCONST.ITMFORM);
          if (!configForm.equalsIgnoreCase(docForm)) {
            if (LOGGER.isLoggable(Level.FINEST)) {
              LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
                  "Skipping metafields because configured form {0} does not "
                  + "match doc form {1}",
                  new Object[] { configForm, docForm });
            }
            continue;
          }
        }
        if (!srcDoc.hasItem(mf.getFieldName())) {
          if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
                "Source doc does not have field: " + mf.getFieldName());
          }
          continue;
        }
        // If there are multiple items with the same name (not a
        // common Notes occurrence), only the first item will be
        // mapped.
        item = srcDoc.getFirstItem(mf.getFieldName());
        if (null == item.getValues()) {
          if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
                "Source doc does not have value for: " + mf.getFieldName());
          }
          continue;
        }
        Object content = item;
        if (item.getType() == NotesItem.RICHTEXT) {
          content = item.getText(2 * 1024);
        }
        if (crawlDoc.hasItem(META_FIELDS_PREFIX + mf.getMetaName())) {
          LOGGER.logp(Level.WARNING, CLASS_NAME, METHOD,
              "Mapping meta fields: meta field {0} already exists in crawl doc",
              mf.getMetaName());
          // If multiple Notes fields are mapped to the same meta
          // field, only the first mapping will be used.
          continue;
        }
        crawlDoc.replaceItemValue(META_FIELDS_PREFIX + mf.getMetaName(),
            content);
        if (LOGGER.isLoggable(Level.FINEST)) {
          LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
              "Mapped meta field : " + META_FIELDS_PREFIX
              + mf.getMetaName() + " =  " + content);
        }
      } catch (RepositoryException e) {
        LOGGER.logp(Level.WARNING, CLASS_NAME, METHOD,
            "Error mapping MetaField " + mf, e);
      } finally {
        if (null != item) {
          item.recycle();
        }
      }
    }
    LOGGER.exiting(CLASS_NAME, METHOD);
  }

  protected String getHTTPURL(NotesDocument crawlDoc)
      throws RepositoryException {

    String httpURL = null;
    String server = null;

    // Get the domain name associated with the server
    server = crawlDoc.getItemValueString(NCCONST.NCITM_SERVER);
    String domain = ncs.getDomain(server);

    httpURL = String.format("http://%s%s/%s/0/%s",
        crawlDoc.getItemValueString(NCCONST.NCITM_SERVER),
        domain,
        crawlDoc.getItemValueString(NCCONST.NCITM_REPLICAID),
        crawlDoc.getItemValueString(NCCONST.NCITM_UNID));
    return httpURL;
  }

  protected String getContentFields(NotesDocument srcDoc)
      throws RepositoryException {
    final String METHOD = "getContentFields";
    LOGGER.entering(CLASS_NAME, METHOD);

    // TODO:  Handle stored forms
    StringBuffer content = new StringBuffer();
    // If we have a form document then we have a specified list
    // of fields to index
    if (null != formDoc) {
      Vector<?> v = formDoc.getItemValue(NCCONST.FITM_FIELDSTOINDEX);
      for (int i = 0; i < v.size(); i++) {
        String fieldName = v.elementAt(i).toString();
        // Fields beginning with $ are reserved fields in Domino
        // Do not index the Form field ever
        if ((fieldName.charAt(0) == '$') ||
            (fieldName.equalsIgnoreCase("form"))) {
          continue;
        }
        content.append("\n");
        NotesItem tmpItem = srcDoc.getFirstItem(fieldName);
        if (null != tmpItem) {
          // Must use getText to get more than 64k of text
          content.append(tmpItem.getText(2 * 1024 * 1024));
          tmpItem.recycle();
        }
      }
      LOGGER.exiting(CLASS_NAME, METHOD);
      return content.toString();
    }

    // Otherwise we will index all allowable fields
    Vector <?> vi = srcDoc.getItems();
    for (int j = 0; j < vi.size(); j++) {
      NotesItem itm = (NotesItem) vi.elementAt(j);
      String ItemName = itm.getName();
      if ((ItemName.charAt(0) == '$') || (ItemName.equalsIgnoreCase("form"))) {
        continue;
      }
      int type = itm.getType();
      switch (type) {
        case NotesItem.TEXT:
        case NotesItem.NUMBERS:
        case NotesItem.DATETIMES:
        case NotesItem.RICHTEXT:
        case NotesItem.NAMES:
        case NotesItem.AUTHORS:
        case NotesItem.READERS:
          content.append("\n");
          NotesItem tmpItem = srcDoc.getFirstItem(ItemName);
          if (null != tmpItem) {
            // Must use getText to get more than 64k of text
            content.append(tmpItem.getText(2 * 1024 * 1024));
            tmpItem.recycle();
          }
          break;
        default:
          break;
      }
    }
    LOGGER.exiting(CLASS_NAME, METHOD);
    return content.toString();
  }

  protected boolean prefetchDoc(NotesDocument crawlDoc) {
    final String METHOD = "prefetchDoc";
    LOGGER.entering(CLASS_NAME, METHOD);

    String NotesURL = null;
    NotesDocument srcDoc = null;
    try {
      NotesURL = crawlDoc.getItemValueString(NCCONST.ITM_GMETANOTESLINK);
      LOGGER.logp(Level.FINER, CLASS_NAME, METHOD,
          "Prefetching document " + NotesURL);

      // Get the template for this document
      loadTemplateDoc(crawlDoc.getItemValueString(NCCONST.NCITM_TEMPLATE));
      if (null == templateDoc) {
        LOGGER.logp(Level.FINER, CLASS_NAME, METHOD,
            "No template found for document " +
            crawlDoc.getItemValueString(NCCONST.ITM_GMETANOTESLINK));
        return false;
      }

      // Check to see if the database we all ready have open is
      // the right one by comparing replicaids
      String crawlDocDbRepId = crawlDoc.getItemValueString(
          NCCONST.NCITM_REPLICAID);
      if (!crawlDocDbRepId.contentEquals(openDbRepId)) {
        // Different ReplicaId - Recycle and close the old database
        if (srcdb != null) {
          srcdb.recycle();
          srcdb= null;
        }
        // Open the new database
        srcdb = ns.getDatabase(null, null);
        srcdb.openByReplicaID(crawlDoc.getItemValueString(
                NCCONST.NCITM_SERVER), crawlDocDbRepId);
        openDbRepId = crawlDocDbRepId;
      }

      // Load our source document
      srcDoc = srcdb.getDocumentByUNID(crawlDoc.getItemValueString(
              NCCONST.NCITM_UNID));
      // Get the form configuration for this document
      loadForm(srcDoc.getItemValueString(NCCONST.ITMFORM));
      if (null == formDoc) {
        LOGGER.logp(Level.FINER, CLASS_NAME, METHOD,
            "No form definition found.  Using template definition " +
            "to process document " + NotesURL);
      }

      setDocumentReaderNames(crawlDoc, srcDoc);
      setDocumentSecurity(crawlDoc);

      mapFields(crawlDoc, srcDoc);
      mapMetaFields(crawlDoc, srcDoc);

      // Process the attachments associated with this document
      // When there are multiple attachments with the same name
      // Lotus Notes automatically generates unique names for next document
      Vector<?> va = ns.evaluate("@AttachmentNames", srcDoc);
      Vector<String> docIds = new Vector<String>();

      NotesItem attachItems = crawlDoc.replaceItemValue(
          NCCONST.ITM_GMETAATTACHMENTS, "");
      for (int i = 0; i < va.size(); i++) {
        String attachName = va.elementAt(i).toString();

        if (attachName.length() == 0) {
          continue;
        }
        String xtn = null;
        int period = attachName.lastIndexOf(".");
        if (period == -1) {
          xtn = "";
        } else {
          xtn = attachName.substring(period + 1);
        }
        if (!ncs.isExcludedExtension(xtn.toLowerCase())) {
          String docId = createAttachmentDoc(crawlDoc, srcDoc,
              attachName, ncs.getMimeType(xtn));
          if (docId != null) {
            attachItems.appendToTextList(attachName);
            docIds.add(docId);
          } else {
            LOGGER.log(Level.FINER,
                "Attachment document was not created for {0}", attachName);
          }
        } else {
          LOGGER.logp(Level.FINER, CLASS_NAME, METHOD,
              "Excluding attachment in " + NotesURL + " : " + attachName);
        }
      }
      crawlDoc.replaceItemValue(NCCONST.ITM_GMETAALLATTACHMENTS, va);
      crawlDoc.replaceItemValue(NCCONST.ITM_GMETAATTACHMENTDOCIDS, docIds);

      // Get our content after processing attachments
      // We don't want the document content in the attachment docs
      // Our content must be stored as non-summary rich text to
      // avoid the 32/64K limits in Domino
      NotesRichTextItem contentItem = crawlDoc.createRichTextItem(
          NCCONST.ITM_CONTENT);
      String content = getContentFields(srcDoc);
      contentItem.appendText(content);
      contentItem.setSummary(false);

      // Update the status of the document to be fetched.
      crawlDoc.replaceItemValue(NCCONST.ITM_ACTION, ActionType.ADD.toString());
      srcDoc.recycle();

      // Check attachments against H2 database and create delete requests for
      // attachments which no longer exist in source document.
      NotesDocId notesDocId =
          new NotesDocId(crawlDoc.getItemValueString(NCCONST.ITM_DOCID));
      enqueue(notesDocId, docIds);

      return true;
    } catch (Exception e) {
      LOGGER.log(Level.SEVERE, CLASS_NAME, e);
      return false;
    } finally {
      LOGGER.exiting(CLASS_NAME, METHOD);
    }
  }

  /**
   * Create delete requests for attachments which no longer exist in the
   * source document.
   *
   * @param notesId google:docid of the parent document
   * @param attachIds hashes of current attachment names
   */
  void enqueue(NotesDocId notesId, Vector<String> attachIds) {
    LOGGER.log(Level.FINEST, "Send delete requests for attachments which "
        + "no longer exist in source document [UNID: {0}]", notesId);
    Set<String> curAttachIds = new HashSet<String>(attachIds);

    NotesDocumentManager docMgr = ncs.getNotesDocumentManager();
    Connection conn = null;
    try {
      conn = docMgr.getDatabaseConnection();
      Set<String> allAttachIds = docMgr.getAttachmentIds(conn,
          notesId.getDocId(), notesId.getReplicaId());
      for (String attachId : allAttachIds) {
        if (!curAttachIds.contains(attachId)) {
          LOGGER.log(Level.FINEST, "{0} attachment is in cache but not in "
              + "source document, send delete request to GSA", attachId);
          try {
            // Send deletion for each attachment
            String attachmentUrl = String.format(NCCONST.SITM_ATTACHMENTDOCID,
                notesId.toString(), attachId);
            createDeleteRequest(attachmentUrl);
          } catch (RepositoryException e) {
            LOGGER.log(Level.WARNING,
                "Failed to create delete request for attachment: " + attachId);
          }
        }
      }
    } catch (SQLException e) {
      LOGGER.log(Level.SEVERE, "Unable to connect to H2 database", e);
    } finally {
      if (conn != null) {
        docMgr.releaseDatabaseConnection(conn);
      }
    }
  }

  private void createDeleteRequest(String googleDocId)
      throws RepositoryException {
    LOGGER.log(Level.FINEST, "Send deletion request to GSA for {0}",
        googleDocId);
    NotesDocument deleteReq = cdb.createDocument();
    deleteReq.appendItemValue(NCCONST.ITMFORM, NCCONST.FORMCRAWLREQUEST);
    deleteReq.replaceItemValue(NCCONST.ITM_ACTION,
        ActionType.DELETE.toString());
    deleteReq.replaceItemValue(NCCONST.ITM_DOCID, googleDocId);
    deleteReq.replaceItemValue(NCCONST.NCITM_STATE, NCCONST.STATEFETCHED);
    deleteReq.save(true);
    deleteReq.recycle();
  }

  /**
   * Creates a document for an attachment in the GSA Configuration database.  If
   * the file size is exceeding the limit or the MIME type is not supported,
   * only metadata and the attachment file name will be indexed.
   *
   * @param crawlDoc document being crawled in the Crawl Queue view
   * @param srcDoc source document where the attachment is located
   * @param AttachmentName string file name without encoding
   * @param MimeType string MIME type computed from file extension
   * @return attachment document ID string if the attachment document is created
   *         and its content will be indexed.
   *         null string if the attachment document is not created and its
   *         content will not be indexed.
   * @throws RepositoryException if embedded object is not accessible
   */
  @VisibleForTesting
  String createAttachmentDoc(NotesDocument crawlDoc, NotesDocument srcDoc,
      String AttachmentName, String MimeType) throws RepositoryException {
    final String METHOD = "createAttachmentDoc";
    String AttachmentURL = null;
    LOGGER.entering(CLASS_NAME, METHOD);
    NotesEmbeddedObject eo = null;
    NotesDocument attachDoc = null;

    try {
      // Error access the attachment
      eo = srcDoc.getAttachment(AttachmentName);

      if (eo == null) {
        LOGGER.log(Level.FINER, "Attachment could not be accessed {0}",
            AttachmentName);
        return null;
      }

      if (eo.getType() != NotesEmbeddedObject.EMBED_ATTACHMENT) {
        // The object is not an attachment - could be an OLE object or link
        LOGGER.logp(Level.FINER, CLASS_NAME, METHOD,
            "Ignoring embedded object " + AttachmentName);
        eo.recycle();
        return null;
      }

      // Don't send attachments larger than the limit
      if (eo.getFileSize() > ncs.getMaxFileSize()) {
        LOGGER.logp(Level.FINER, CLASS_NAME, METHOD,
            "Attachment larger than the configured limit and content " +
            "will not be sent. " + AttachmentName);
      }

      attachDoc = cdb.createDocument();
      crawlDoc.copyAllItems(attachDoc, true);

      // Store the filename of this attachment in the attachment crawl doc.
      attachDoc.replaceItemValue(NCCONST.ITM_GMETAATTACHMENTFILENAME,
          AttachmentName);
      attachDoc.save();

      // Compute display URL
      String encodedAttachmentName = null;
      try {
        encodedAttachmentName = URLEncoder.encode(AttachmentName, "UTF-8");
      } catch (Exception e) {
        attachDoc.recycle();
        eo.recycle();
        return null;
      }
      AttachmentURL = String.format(NCCONST.SITM_ATTACHMENTDISPLAYURL,
          getHTTPURL(crawlDoc), encodedAttachmentName);
      attachDoc.replaceItemValue(NCCONST.ITM_DISPLAYURL, AttachmentURL);
      LOGGER.log(Level.FINEST, "Attachment display url: {0}", AttachmentURL);

      // Compute docid
      String attachNameHash = Util.hash(AttachmentName);
      if (attachNameHash == null) {
        return null;
      }
      String docURL = String.format(NCCONST.SITM_ATTACHMENTDOCID,
          getHTTPURL(crawlDoc), attachNameHash);
      attachDoc.replaceItemValue(NCCONST.ITM_DOCID, docURL);
      LOGGER.log(Level.FINEST, "Attachment document docid: {0}", docURL);

      // Only if we have a supported mime type and file size is not exceeding
      // the limit do we send the content, or only metadata and file name will
      // be sent.
      if ((0 != MimeType.length()) &&
          eo.getFileSize() <= ncs.getMaxFileSize()) {
        attachDoc.replaceItemValue(NCCONST.ITM_MIMETYPE, MimeType);
        String attachmentPath = getAttachmentFilePath(crawlDoc, attachNameHash);
        eo.extractFile(attachmentPath);
        attachDoc.replaceItemValue(NCCONST.ITM_CONTENTPATH, attachmentPath);
      } else {
        // Not a supported attachment so sending meta data only
        // with the filename as content
        attachDoc.replaceItemValue(NCCONST.ITM_CONTENT, AttachmentName);
        attachDoc.replaceItemValue(NCCONST.ITM_MIMETYPE,
            NCCONST.DEFAULT_MIMETYPE);
      }
      eo.recycle();

      // Set the state of this document to be fetched
      attachDoc.replaceItemValue(NCCONST.ITM_ACTION, ActionType.ADD.toString());
      attachDoc.replaceItemValue(NCCONST.NCITM_STATE, NCCONST.STATEFETCHED);
      attachDoc.save();
      attachDoc.recycle();
      LOGGER.exiting(CLASS_NAME, METHOD);
      return attachNameHash;
    } catch (Exception e) {
      LOGGER.logp(Level.SEVERE, CLASS_NAME, METHOD,
          "Error pre-fetching attachment: " + AttachmentName +
          " in document: " + srcDoc.getNotesURL(), e);
      if (null != eo) {
        eo.recycle();
      }
      if (null != attachDoc) {
        attachDoc.replaceItemValue(NCCONST.NCITM_STATE, NCCONST.STATEERROR);
        attachDoc.save();
        attachDoc.recycle();
      }
      return null;
    }
  }

  // This function will generate an unique file path for an attachment object.
  // Consider the situation where a document is updated twice and
  // appears in the submitq twice In this case, the first submit
  // will delete the doc.  The second submit will then send an
  // empty doc So we must use the UNID of the crawl request to
  // generate the unique filename
  private String getAttachmentFilePath(NotesDocument crawlDoc,
      String attachName) throws RepositoryException {
    String dirName = String.format("%s/attachments/%s/%s",
        ncs.getSpoolDir(),
        cdb.getReplicaID(),
        crawlDoc.getUniversalID());
    new File(dirName).mkdirs();
    String FilePath = String.format("%s/%s", dirName, attachName);
    //TODO:  Ensure that FilePath is a valid Windows filepath
    return FilePath;
  }

  @VisibleForTesting
  void connectQueue() throws RepositoryException {
    if (null == ns) {
      ns = ncs.createNotesSession();
    }
    if (null == cdb) {
      cdb = ns.getDatabase(ncs.getServer(), ncs.getDatabase());
    }
    if (crawlQueue == null) {
      crawlQueue = cdb.getView(NCCONST.VIEWCRAWLQ);
    }
  }

  /*
   * We accumulate objects as pre-fetch documents
   * De-allocate these in reverse order
   */
  private void disconnectQueue()  {
    final String METHOD = "disconnectQueue";
    LOGGER.entering(CLASS_NAME, METHOD);
    try {
      if (null != templateDoc) {
        templateDoc.recycle();
      }
      templateDoc = null;

      if (null != formDoc) {
        formDoc.recycle();
      }
      formDoc = null;

      if (null != formsdc) {
        formsdc.recycle();
      }
      formsdc = null;

      if (null != srcdb) {
        openDbRepId = "";
        srcdb.recycle();
        srcdb = null;
      }

      if (null != crawlQueue) {
        crawlQueue.recycle();
      }
      crawlQueue = null;

      if (null != cdb) {
        cdb.recycle();
      }
      cdb = null;

      if (null != ns) {
        ncs.closeNotesSession(ns);
      }
      ns = null;
    } catch (RepositoryException e) {
      LOGGER.log(Level.WARNING, CLASS_NAME, e);
    } finally {
      LOGGER.exiting(CLASS_NAME, METHOD);
    }
  }

  @Override
  public void run() {
    final String METHOD = "run";
    int exceptionCount = 0;
    LOGGER.entering(CLASS_NAME, METHOD);
    NotesPollerNotifier npn = ncs.getNotifier();
    while (nc.getShutdown() == false) {
      try {
        NotesDocument crawlDoc = null;
        // Only get from the queue if there is more than 300MB in the
        // spool directory
        File spoolDir = new File(ncs.getSpoolDir());
        LOGGER.logp(Level.FINE, CLASS_NAME, METHOD,
            "Spool free space is " + spoolDir.getFreeSpace());
        if (spoolDir.getFreeSpace()/1000000 < 300) {
          LOGGER.logp(Level.WARNING, CLASS_NAME, METHOD,
              "Insufficient space in spool directory to process " +
              "new documents.  Need at least 300MB.");
          npn.waitForWork();
          LOGGER.logp(Level.FINE, CLASS_NAME, METHOD,
              "Crawler thread resuming after spool directory had " +
              "insufficient space.");
          continue;
        }
        LOGGER.logp(Level.FINEST, CLASS_NAME, METHOD,
            "Connecting to crawl queue.");
        connectQueue();
        crawlDoc = getNextFromCrawlQueue(ns, crawlQueue);
        if (crawlDoc == null) {
          LOGGER.logp(Level.FINE, CLASS_NAME, METHOD, this.getName() +
              ": Crawl queue is empty.  Crawler thread sleeping.");
          // If we have finished processing the queue shutdown our connections
          disconnectQueue();
          npn.waitForWork();
          LOGGER.logp(Level.FINE, CLASS_NAME, METHOD, this.getName() +
              "Crawler thread resuming after crawl queue was empty.");
          continue;
        }
        if (prefetchDoc(crawlDoc)) {
          crawlDoc.replaceItemValue(NCCONST.NCITM_STATE, NCCONST.STATEFETCHED);
        } else  {
          crawlDoc.replaceItemValue(NCCONST.NCITM_STATE, NCCONST.STATEERROR);
        }
        crawlDoc.save(true);
        crawlDoc.recycle();
      } catch (Exception e) {
        LOGGER.log(Level.SEVERE, CLASS_NAME, e);
        // Lets say the server we are connected to goes down
        // while we are crawling We don't want to fill up the
        // logs with errors so go to sleep after 5 exceptions
        exceptionCount++;

        // If we run into an exception we should close our session.
        disconnectQueue();

        if (exceptionCount > 5) {
          LOGGER.logp(Level.WARNING, CLASS_NAME, METHOD,
              "Too many exceptions.  Crawler thread sleeping.");
          npn.waitForWork();
          LOGGER.logp(Level.WARNING, CLASS_NAME, METHOD,
              "Crawler thread resuming after too many exceptions " +
              "were encountered.");
        }
      }
    }
    disconnectQueue();
    LOGGER.logp(Level.FINE, CLASS_NAME, METHOD,
        "Connector shutdown - NotesCrawlerThread exiting.");
    LOGGER.exiting(CLASS_NAME, METHOD);
  }

  @VisibleForTesting
  static class MetaField {
    private static final Pattern formFieldMetaPattern =
        Pattern.compile("\\A(.+)===([^=]+)=([^=]+)\\z");
    private static final Pattern fieldMetaPattern =
        Pattern.compile("\\A([^=]+)=([^=]+)\\z");
    private static final Pattern fieldPattern =
        Pattern.compile("\\A([^=]+)\\z");

    private String formName;
    private String fieldName;
    private String metaName;

    MetaField(String configString) {
      String METHOD = "MetaField";
      if (configString == null) {
        return;
      }
      configString = configString.trim();
      if (configString.length() == 0) {
        return;
      }

      Matcher matcher = formFieldMetaPattern.matcher(configString);
      if (matcher.matches()) {
        formName = matcher.group(1);
        fieldName = matcher.group(2);
        metaName = matcher.group(3);
        return;
      }
      matcher = fieldMetaPattern.matcher(configString);
      if (matcher.matches()) {
        fieldName = matcher.group(1);
        metaName = matcher.group(2);
        return;
      }
      matcher = fieldPattern.matcher(configString);
      if (matcher.matches()) {
        fieldName = matcher.group(1);
        metaName = fieldName;
        return;
      }
      LOGGER.logp(Level.WARNING, CLASS_NAME, METHOD,
          "Unable to parse custom meta field definition; skipping: "
          + configString);
    }

    String getFormName() {
      return formName;
    }

    String getFieldName() {
      return fieldName;
    }

    String getMetaName() {
      return metaName;
    }

    @Override
    public String toString() {
      return "[form: " + formName + "; field: " + fieldName
          + "; meta: " + metaName + "]";
    }
  }
}


text:
phparia - PHP ARI API
===

[![Latest Stable Version](https://img.shields.io/packagist/v/wormling/phparia.svg)](https://packagist.org/packages/wormling/phparia) [![Build Status](http://img.shields.io/travis/wormling/phparia.svg?branch=master)](https://travis-ci.org/wormling/phparia) [![Code Coverage](https://scrutinizer-ci.com/g/wormling/phparia/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/wormling/phparia/?branch=master) [![Scrutinizer Quality Score](http://img.shields.io/scrutinizer/g/wormling/phparia.svg)](https://scrutinizer-ci.com/g/wormling/phparia/) [![Dependency Status](https://www.versioneye.com/user/projects/558fd8a5316338001a000515/badge.svg?style=flat)](https://www.versioneye.com/user/projects/558fd8a5316338001a000515)[![License](https://img.shields.io/github/license/wormling/phparia.svg)](http://www.apache.org/licenses/LICENSE-2.0)

Framework for creating Asterisk 12/13 ARI applications.  (https://wiki.asterisk.org/wiki/display/AST/Getting+Started+with+ARI)

Features
---

* Full Asterisk REST Interface support (Tested with 12 and 13)
* Event system at the client and resource level
* Optional basic AMI event/action support
* Verbose for ease of use
* Partial functional tests TODO!

Available via Composer
---
Just add the package "wormling/phparia":

```yaml
    {
        "require": {
            "wormling/phparia": "dev-master"
        }
    }
```

Creating a stasis application
---
```php
    $ariAddress = 'ws://localhost:8088/ari/events?api_key=username:password&app=stasis_app_name';

    $logger = new \Zend\Log\Logger();
    $logWriter = new \Zend\Log\Writer\Stream("php://output");
    $logger->addWriter($logWriter);
    //$filter = new \Zend\Log\Filter\SuppressFilter(true);
    $filter = new \Zend\Log\Filter\Priority(\Zend\Log\Logger::NOTICE);
    $logWriter->addFilter($filter);

    $this->client = new \phparia\Client\Phparia($logger);
    $this->client->connect($ariAddress);
    $this->client->onStasisStart(function(StasisStart $event) {
        $channel = $event->getChannel();
        $bridge = $this->client->bridges()->createBridge(uniqid(), 'dtmf_events, mixing', 'bridgename');
        $this->client->bridges()->addChannel($bridge->getId(), $channel->getId(), null);

        ...
    });

    $this->client->run();
```

Creating a stasis application and listening for AMI events
---
```php
    $ariAddress = 'ws://localhost:8088/ari/events?api_key=username:password&app=stasis_app_name';
    $amiAddress = 'username:password@localhost:5038';

    $logger = new \Zend\Log\Logger();
    $logWriter = new \Zend\Log\Writer\Stream("php://output");
    $logger->addWriter($logWriter);
    //$filter = new \Zend\Log\Filter\SuppressFilter(true);
    $filter = new \Zend\Log\Filter\Priority(\Zend\Log\Logger::NOTICE);
    $logWriter->addFilter($filter);

    $this->client = new \phparia\Client\Phparia($logger);
    $this->client->connect($ariAddress, $amiAddress);
    $this->client->onStasisStart(function(StasisStart $event) {
        $channel = $event->getChannel();
        $bridge = $this->client->bridges()->createBridge(uniqid(), 'dtmf_events, mixing', 'bridgename');
        $this->client->bridges()->addChannel($bridge->getId(), $channel->getId(), null);

        $this->client->getWsClient()->on('SomeAMIEventName', function($event) {
            ...
        });

        ...
    });

    $this->client->run();
```

Documentation
---
You will find wrappers for (https://wiki.asterisk.org/wiki/display/AST/Asterisk+13+ARI) in the Api folder.

You will find wrappers for (https://wiki.asterisk.org/wiki/display/AST/Asterisk+13+REST+Data+Models) in the Resources and Events folders.

Examples
---
(https://github.com/wormling/phparia/tree/master/src/wormling/phparia/Examples)

(https://github.com/wormling/phparia/tree/master/src/wormling/phparia/Tests/Functional)

Extensions
---
[phparia-lyra](https://github.com/wormling/phparia-lyra) [Sangoma Lyra Answering Machine Detection for Asterisk.](http://www.sangoma.com/products/answering-machine-detection-for-asterisk-sangoma-lyra)

License
---
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)


text:
Handlebars.registerHelper( 'ifCond', function( v1, operator, v2, options ){
    switch( operator ){
        case '==':
            return ( v1 == v2 ) ? options.fn( this ) : options.inverse( this );
        case '===':
            return ( v1 === v2 ) ? options.fn( this ) : options.inverse( this );
        case '<':
            return ( v1 < v2 ) ? options.fn( this ) : options.inverse( this );
        case '<=':
            return ( v1 <= v2 ) ? options.fn( this ) : options.inverse( this );
        case '>':
            return ( v1 > v2 ) ? options.fn( this ) : options.inverse( this );
        case '>=':
            return ( v1 >= v2 ) ? options.fn( this ) : options.inverse( this );
        case '&&':
            return ( v1 && v2 ) ? options.fn( this ) : options.inverse( this );
        case '||':
            return ( v1 || v2 ) ? options.fn( this ) : options.inverse( this );
        default:
            return options.inverse( this );
    }
});

// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
  Object.keys = (function() {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function(obj) {
      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }

      var result = [], prop, i;

      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}

(function( $ ){
    'use strict';
    var matches = {
            matches : {},
            templates : {},
            countries : {},
            $matchesList : $( '.js-matches' ),
            $progressBar : $( '.js-progress-bar' ),
            $noMatches : $( '.js-no-matches' ),
            requestsSent : 0,
            unknownTeamIdentifier : '-unknown-',
            requestsDone : 0,
            init : function(){
                var _this = this;

                this.loadTemplates();
                this.loadStreams();
                this.loadCountries();

                setInterval( function(){
                    _this.loadStreams();
                }, 60000 );

                $( 'body' ).on( 'click touchstart', '.js-close', function( event ){
                    event.preventDefault();
                    event.stopImmediatePropagation();
                    $( this ).parents( '.js-match-wrapper' ).removeClass( 'active' );
                });

                $( 'body' ).on( 'click touchstart', '.js-match-wrapper', function(){
                    var $element = $( this ),
                        windowHeight = $( window ).height(),
                        elementHeight,
                        offset = 0;

                    $( '.active' ).removeClass( 'active' );
                    $element.addClass( 'active' );

                    elementHeight = $element.height();

                    if( windowHeight > elementHeight ){
                        offset = -( ( windowHeight - elementHeight ) / 2 )
                    }

                    $element
                        .velocity( 'stop' )
                        .velocity({
                            scale: '1'
                        }, 300 )
                        .velocity( 'scroll', {
                            offset : offset,
                            queue : false
                        });
                });

                $( 'body' ).on( 'mouseenter', '.js-match-wrapper', function(){
                    var $element = $( this );

                    if( !$element.hasClass( 'active' ) ){
                        $( this ).velocity( 'stop' ).velocity({
                            scale: '1.1'
                        }, 300 );
                    }
                });

                $( 'body' ).on( 'mouseleave', '.js-match-wrapper', function(){
                    $( this ).velocity({
                        scale: '1'
                    }, 300 );
                });

                $( 'body' ).on( 'mouseenter', '.js-match-wrapper .js-stream-row', function(){
                    $( this ).find( '.js-panel-background' ).velocity( 'stop' ).velocity({
                        opacity: '0.2'
                    }, 300 );
                });

                $( 'body' ).on( 'mouseleave', '.js-stream-row', function(){
                    $( this ).find( '.js-panel-background' ).velocity( 'stop' ).velocity({
                        opacity: '0'
                    }, 300 );
                });
            },
            loadStreams : function(){
                this.loadData( 'hitbox' );
                this.loadData( 'twitch' );
                this.loadData( 'azubu' );
                this.loadData( 'mlg' );
            },
            loadTemplates : function(){
                this.loadTemplate( 'match' );
                this.loadTemplate( 'stream' );
            },
            loadCountries : function(){
                var _this = this,
                    xhr = $.ajax({
                        url: 'resources/countries.json'
                    });

                this.requestsSent = this.requestsSent + 1;

                xhr.done(function( response ){
                    _this.requestsDone = _this.requestsDone + 1;

                    _this.updateProgressbar();

                    _this.handleCountriesLoad( response );
                });
            },
            handleCountriesLoad : function( countriesData ){
                var i;

                for( i = 0; i < countriesData.length; i = i + 1 ){
                    this.countries[ countriesData[ i ].name.toLowerCase() ] = countriesData[ i ][ 'alpha-2' ].toLowerCase();
                }
            },
            loadTemplate : function( template ){
                var _this = this,
                    xhr = $.ajax({
                        url: 'resources/templates/' + template + '.handlebars'
                    });

                this.requestsSent = this.requestsSent + 1;

                xhr.done(function( response ){
                    _this.requestsDone = _this.requestsDone + 1;

                    _this.updateProgressbar();

                    _this.templates[ template ] = Handlebars.compile( response );
                });
            },
            loadData : function( service ){
                var _this = this,
                    xhr = $.ajax({
                        url: 'matches-ajax.php',
                        data: {
                            'site': service
                        }
                    });

                this.requestsSent = this.requestsSent + 1;

                xhr.done(function( response ){
                    _this.requestsDone = _this.requestsDone + 1;

                    _this.updateProgressbar();

                    _this.handleResponse( response, service );
                });
            },
            getMatchIdentifier : function( match ){
                return [ match.teams[ 0 ].identifier, match.teams[ 1 ].identifier ].sort().toString();
            },
            handleResponse : function( response, service ){
                var _this = this;

                // Add frontend data to each match
                $.each( response, function( matchIndex, matchData ){
                    var numberOfCountries = 0;

                    $.each( matchData.streams, function( streamIndex, streamData ){
                        response[ matchIndex ].streams[ streamIndex ].live = 1;
                    });

                    $.each( matchData.teams, function( teamIndex, teamData ){
                        if( _this.countries[ teamData.identifier ] !== undefined ){
                            response[ matchIndex ].teams[ teamIndex ].country = _this.countries[ teamData.identifier ];
                            numberOfCountries = numberOfCountries + 1;
                        }
                    });

                    // Special case when we actually match only one country
                    if( numberOfCountries > 0 && numberOfCountries < matchData.teams.length ){
                        $.each( matchData.teams, function( teamIndex, teamData ){
                            if( response[ matchIndex ].teams[ teamIndex ].country ) {
                                delete response[ matchIndex ].teams[ teamIndex ].country;
                            }

                            response[ matchIndex ].teams[ teamIndex ].identifier = _this.unknownTeamIdentifier;
                            response[ matchIndex ].teams[ teamIndex ].name = '???';
                        });
                    }
                });

                // Loop over all matches we got in the response
                $.each( response, function( index, data ){
                    var identifier = _this.getMatchIdentifier( data );

                    // The match isn't listed, just add the data from the response
                    if( _this.matches[ identifier ] === undefined ){
                        _this.matches[ identifier ] = data;
                    } else {
                        // Loop over all the matches streams
                        $.each( _this.matches[ identifier ].streams, function( streamIndex, streamData ){
                            // Check if the stream is already listed for that particular match
                            $.each( data.streams, function( dataStreamIndex, dataStreamData ){
                                if( streamData.name == dataStreamData.name ){
                                    // The stream is listed, update data and remove it from the raw response
                                    _this.matches[ identifier ].streams[ streamIndex ] = dataStreamData;
                                    data.streams.splice( dataStreamIndex, 1 );
                                    return false;
                                }
                            });
                        });

                        // Data streams should only hold streams that are not already listed, so add them
                        _this.matches[ identifier ].streams = _this.matches[ identifier ].streams.concat( data.streams );
                    }
                });

                // Loop over all matches
                $.each( _this.matches, function( matchIndex, matchData ){
                    if( matchData.streams.length > 0 ){
                        // Loop over all a match's streams
                        $.each( matchData.streams, function( streamIndex, streamData ){
                            // Check if the stream matches the service and isn't live
                            if( streamData.service === service && !streamData.live ){
                                _this.matches[ matchIndex ].streams.splice( streamIndex, 1 );
                            } else if( streamData.service === service ){
                                _this.matches[ matchIndex ].streams[ streamIndex ].live = false;
                            }
                        });
                    }

                    // If a match doesn't have any streams any more, remove it
                    if( matchData.streams.length === 0 ){
                        delete _this.matches[ matchIndex ];
                        $( '[data-identifier="' + _this.getMatchIdentifier( matchData ) + '"]' ).velocity( 'transition.fadeOut', {
                            complete : function( element ){
                                $( element ).remove();
                            }
                        });

                        return true;
                    }
                });

                this.updateData();
            },
            updateProgressbar : function(){
                var _this = this;

                if( this.$progressBar.length > 0 ){
                    if( this.requestsSent == this.requestsDone ) {
                        this.$progressBar.css({
                            width: '100%'
                        });

                        // Try to wait until the progressbar is filled before removing it
                        setTimeout( function(){
                            _this.$progressBar.remove();
                        }, 600 );
                    } else {
                        this.$progressBar.css({
                            width: ( _this.requestsDone / _this.requestsSent * 100 ).toString() + '%'
                        });
                    }
                }

            },
            renderMatch : function( match ){
                var $markup,
                    streamIndex,
                    _this = this,
                    $streamsWrapper,
                    matchIdentifier = _this.getMatchIdentifier( match );

                if( !match.rendered ){
                    if( matchIdentifier === this.unknownTeamIdentifier + ',' + this.unknownTeamIdentifier ){
                        $markup = $( '.js-unknown-matches' ).attr( 'data-identifier', matchIdentifier  );
                        match.rendered = true;
                    } else {
                        $markup = $( this.templates[ 'match' ]( match ) )
                            .attr( 'data-identifier', matchIdentifier  )
                            .css({
                                opacity: 0
                            });
                    }
                } else {
                    $markup = $( '[data-identifier="' + matchIdentifier + '"]' );
                }

                $streamsWrapper = $markup.find( '.js-streams-wrapper' );

                for( streamIndex = 0; streamIndex < match.streams.length; streamIndex = streamIndex + 1 ){
                    this.renderStream( match.streams[ streamIndex ], $streamsWrapper );
                }

                if( !match.rendered ){
                    this.$matchesList.append( $markup );
                    $markup.velocity( 'transition.fadeIn', {
                        stagger: 250
                    });

                    match.rendered = true;
                }

                // Remove streams that are no longer live
                $markup.find( '.js-stream-row' ).not( '[data-live="yes"]' ).remove().end().removeAttr( 'data-live' );
            },
            renderStream : function( stream, $wrapperMarkup ){
                var $streamMarkup,
                    streamIdentifier = stream.service + '.' + stream.name,
                    $renderedStream = $wrapperMarkup.find( '[data-identifier="' + streamIdentifier + '"]' );

                $streamMarkup = $( this.templates[ 'stream' ]( stream ) )
                    .attr( 'data-identifier', streamIdentifier )
                    .attr( 'data-live', 'yes' );

                $streamMarkup.popover({
                    container: 'body',
                    mouseOffset: 20,
                    followMouse: true
                });

                if( $renderedStream.length > 0 ){
                    $renderedStream.replaceWith( $streamMarkup );
                } else {
                    $wrapperMarkup.append( $streamMarkup );
                }
            },
            updateData : function(){
                var matchIdentifier,
                    _this = this,
                    numberOfMatches = Object.keys( this.matches ).length;

                if( this.matches === {} && this.templates === false ){
                    setTimeout( function(){
                        matches.updateData();
                    }, 50 );

                    return false;
                }

                if( this.requestsSent == this.requestsDone ) {
                    this.updateProgressbar();

                    if( numberOfMatches === 0 ){
                        this.$noMatches.show();
                    }
                }

                if( numberOfMatches > 0 ){
                    $( '.popover' ).remove();
                    this.$noMatches.hide();

                    for( matchIdentifier in this.matches ){
                        if( this.matches.hasOwnProperty( matchIdentifier ) ){
                            this.renderMatch( this.matches[ matchIdentifier ] );
                        }
                    }
                }

                // Show and hide headers as neccesary
                if( $( '.js-matches' ).find( '.js-stream-row' ).length > 0 ){
                    $( '.js-matches' ).find( 'h1' ).css({
                        display: 'block'
                    });
                } else {
                    $( '.js-matches' ).find( 'h1' ).css({
                        display: 'none'
                    });
                }

                if( $( '.js-unknown-matches' ).find( '.js-stream-row' ).length > 0 ){
                    $( '.js-unknown-matches' ).find( 'h2' ).css({
                        display: 'block'
                    });
                } else {
                    $( '.js-unknown-matches' ).find( 'h2' ).css({
                        display: 'none'
                    });
                }
            }
        };

    window.matches = matches;

    $(function(){
        matches.init();
    });
})( $ );


text:
package com.sentenial.rest.client.api.originator.dto;

public class Originator {
    private OriginatorDetails originatorDetails;
    private Address address;
    private PrimaryContact primaryContact;

    public OriginatorDetails getOriginatorDetails() {
        return originatorDetails;
    }

    public void setOriginatorDetails(OriginatorDetails originatorDetails) {
        this.originatorDetails = originatorDetails;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public PrimaryContact getPrimaryContact() {
        return primaryContact;
    }

    public void setPrimaryContact(PrimaryContact primaryContact) {
        this.primaryContact = primaryContact;
    }

}


text:
#include "squash.h"
#include <stdlib.h>

struct squash_fdtable squash_global_fdtable;
MUTEX squash_global_mutex;

int squash_open_inner(sqfs *fs, const char *path, short follow_link)
{
	sqfs_err error;
	struct squash_file *file = calloc(1, sizeof(struct squash_file));
	short found;
	int fd;
	size_t nr;
	int *handle;

	// try locating the file and fetching its stat
	if (NULL == file)
	{
		errno = ENOMEM;
		return -1;
	}
	error = sqfs_inode_get(fs, &file->node, sqfs_inode_root(fs));
	if (SQFS_OK != error)
	{
		goto failure;
	}
	error = sqfs_lookup_path_inner(fs, &file->node, path, &found, follow_link);
	if (SQFS_OK != error)
	{
		goto failure;
	}
	file->filename = strdup(path);

	if (!found)
	{
		errno = ENOENT;
		goto failure;
	}
	error = sqfs_stat(fs, &file->node, &file->st);
	if (SQFS_OK != error)
	{
		goto failure;
	}
	file->fs = fs;
	file->pos = 0;

	// get a dummy fd from the system
	fd = dup(0);
	if (-1 == fd) {
		goto failure;
	}
	// make sure that our global fd table is large enough
	nr = fd + 1;

	MUTEX_LOCK(&squash_global_mutex);
	if (squash_global_fdtable.nr < nr)
	{
		// we secretly extend the requested size
		// in order to minimize the number of realloc calls
		nr *= 10;
		squash_global_fdtable.fds = realloc(squash_global_fdtable.fds,
						    nr * sizeof(struct squash_file *));
		if (NULL == squash_global_fdtable.fds)
		{
			errno = ENOMEM;
			goto failure;
		}
		memset(squash_global_fdtable.fds + squash_global_fdtable.nr,
		       0,
		       (nr - squash_global_fdtable.nr) * sizeof(struct squash_file *));
		squash_global_fdtable.nr = nr;
	}
	MUTEX_UNLOCK(&squash_global_mutex);

	// construct a handle (mainly) for win32
	handle = (int *)malloc(sizeof(int));
	if (NULL == handle) {
		errno = ENOMEM;
		goto failure;
	}
	*handle = fd;
	file->payload = (void *)handle;

	// insert the fd into the global fd table
	file->fd = fd;
	MUTEX_LOCK(&squash_global_mutex);
	squash_global_fdtable.fds[fd] = file;
        if (squash_global_fdtable.end < fd + 1) {
        	squash_global_fdtable.end = fd + 1;
        }
	MUTEX_UNLOCK(&squash_global_mutex);
	return fd;

failure:
	if (!errno) {
		errno = ENOENT;
	}
	free(file);
	return -1;
}

int squash_open(sqfs *fs, const char *path)
{
        return squash_open_inner(fs, path, 1);
}

int squash_close(int vfd)
{
	int ret;
	struct squash_file *file;

        if (!SQUASH_VALID_VFD(vfd)) {
                errno = EBADF;
                return -1;
        }
        ret = close(vfd);
	if (-1 == ret) {
		return -1;
	}
        MUTEX_LOCK(&squash_global_mutex);
        if (S_ISDIR(squash_global_fdtable.fds[vfd]->st.st_mode)) {
                SQUASH_DIR *dir = (SQUASH_DIR *) (squash_global_fdtable.fds[vfd]->payload);
                free(dir);
        } else {
                int *handle = (int *) (squash_global_fdtable.fds[vfd]->payload);
                free(handle);
        }

        file = squash_global_fdtable.fds[vfd];
        free(file->filename);
        free(file);

        squash_global_fdtable.fds[vfd] = NULL;
        if (vfd + 1 == squash_global_fdtable.end) {
                while (vfd >= 0 && NULL == squash_global_fdtable.fds[vfd]) {
                        vfd -= 1;
                }
                squash_global_fdtable.end = vfd + 1;
        } else {
                assert(squash_global_fdtable.end > vfd + 1);
        }
        MUTEX_UNLOCK(&squash_global_mutex);
        return 0;
}

ssize_t squash_read(int vfd, void *buf, sqfs_off_t nbyte)
{
	sqfs_err error;
	struct squash_file *file;

	if (!SQUASH_VALID_VFD(vfd))
	{
		errno = EBADF;
		goto failure;
	}
	file = squash_global_fdtable.fds[vfd];

	error = sqfs_read_range(file->fs, &file->node, file->pos, &nbyte, buf);
	if (SQFS_OK != error)
	{
		goto failure;
	}
	file->pos += nbyte;
	return nbyte;
failure:
	if (!errno) {
		errno = EBADF;
	}
	return -1;
}

off_t squash_lseek(int vfd, off_t offset, int whence)
{
	struct squash_file *file;
	if (!SQUASH_VALID_VFD(vfd))
	{
		errno = EBADF;
		return -1;
	}
	file = squash_global_fdtable.fds[vfd];
	if (SQUASH_SEEK_SET == whence)
	{
		file->pos = offset;
	}
	else if (SQUASH_SEEK_CUR == whence)
	{
		file->pos += offset;
	}
	else if (SQUASH_SEEK_END == whence)
	{
		assert(S_ISREG(file->node.base.mode));
		file->pos = file->node.xtra.reg.file_size;
	}
	return file->pos;
}

static void squash_halt()
{
	if (squash_global_fdtable.fds) {
		free(squash_global_fdtable.fds);
	}
	MUTEX_DESTORY(&squash_global_mutex);
	squash_extract_clear_cache();
}

sqfs_err squash_start()
{
	int ret;
	squash_global_fdtable.nr = 0;
	squash_global_fdtable.fds = NULL;
	MUTEX_INIT(&squash_global_mutex);
	ret = atexit(squash_halt);
	if (0 == ret) {
		return SQFS_OK;
	} else {
		return SQFS_ERR;
	}
}

struct squash_file * squash_find_entry(void *ptr)
{
	size_t i;
	struct squash_file * ret = NULL;
	MUTEX_LOCK(&squash_global_mutex);
	for (i = 0; i < squash_global_fdtable.end; ++i) {
		if (squash_global_fdtable.fds[i] && ptr == squash_global_fdtable.fds[i]->payload) {
			ret = squash_global_fdtable.fds[i];
			break;
		}
	}
	MUTEX_UNLOCK(&squash_global_mutex);
	return ret;
}


text:
package org.apache.uima.fit.component;

import java.util.Map;

import org.apache.uima.fit.component.initialize.ConfigurationParameterInitializer;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.factory.ExternalResourceFactory;
import org.apache.uima.fit.internal.ExtendedLogger;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.resource.ResourceSpecifier;

/**
 * Base class for external resources which initializes itself based on annotations.
 *
 */
public abstract class Resource_ImplBase extends org.apache.uima.resource.Resource_ImplBase
        implements ExternalResourceAware {

  private ExtendedLogger logger;

  @ConfigurationParameter(name = ExternalResourceFactory.PARAM_RESOURCE_NAME, mandatory = false)
  private String resourceName;

  @Override
  public ExtendedLogger getLogger() {
    if (logger == null) {
      logger = new ExtendedLogger(getUimaContext());
    }
    return logger;
  }

  @Override
  public boolean initialize(final ResourceSpecifier aSpecifier,
          final Map<String, Object> aAdditionalParams) throws ResourceInitializationException {
    if (!super.initialize(aSpecifier, aAdditionalParams)) {
      return false;
    }

    ConfigurationParameterInitializer.initialize(this, aSpecifier);
    // We cannot call ExternalResourceInitializer.initialize() because the
    // ResourceManager_impl has not added the resources to the context yet.
    // Resource initialization is handled by ExternalResourceInitializer.initialize()
    // when it is called on the first pipeline component.

    return true;
  }

  public String getResourceName() {
    return resourceName;
  }

  public void afterResourcesInitialized() throws ResourceInitializationException {
    // Per default nothing is done here.
  }
}


text:
'use strict';

var _extends = require('babel-runtime/helpers/extends')['default'];

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _BootstrapMixin = require('./BootstrapMixin');

var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);

var _utilsCustomPropTypes = require('./utils/CustomPropTypes');

var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);

var _ButtonInput = require('./ButtonInput');

var _ButtonInput2 = _interopRequireDefault(_ButtonInput);

var Button = _react2['default'].createClass({
  displayName: 'Button',

  mixins: [_BootstrapMixin2['default']],

  propTypes: {
    active: _react2['default'].PropTypes.bool,
    disabled: _react2['default'].PropTypes.bool,
    block: _react2['default'].PropTypes.bool,
    navItem: _react2['default'].PropTypes.bool,
    navDropdown: _react2['default'].PropTypes.bool,
    /**
     * You can use a custom element for this component
     */
    componentClass: _utilsCustomPropTypes2['default'].elementType,
    href: _react2['default'].PropTypes.string,
    target: _react2['default'].PropTypes.string,
    /**
     * Defines HTML button type Attribute
     * @type {("button"|"reset"|"submit")}
     * @defaultValue 'button'
     */
    type: _react2['default'].PropTypes.oneOf(_ButtonInput2['default'].types)
  },

  getDefaultProps: function getDefaultProps() {
    return {
      active: false,
      block: false,
      bsClass: 'button',
      bsStyle: 'default',
      disabled: false,
      navItem: false,
      navDropdown: false
    };
  },

  render: function render() {
    var classes = this.props.navDropdown ? {} : this.getBsClassSet();
    var renderFuncName = undefined;

    classes = _extends({
      active: this.props.active,
      'btn-block': this.props.block
    }, classes);

    if (this.props.navItem) {
      return this.renderNavItem(classes);
    }

    renderFuncName = this.props.href || this.props.target || this.props.navDropdown ? 'renderAnchor' : 'renderButton';

    return this[renderFuncName](classes);
  },

  renderAnchor: function renderAnchor(classes) {

    var Component = this.props.componentClass || 'a';
    var href = this.props.href || '#';
    classes.disabled = this.props.disabled;

    return _react2['default'].createElement(
      Component,
      _extends({}, this.props, {
        href: href,
        className: _classnames2['default'](this.props.className, classes),
        role: 'button' }),
      this.props.children
    );
  },

  renderButton: function renderButton(classes) {
    var Component = this.props.componentClass || 'button';

    return _react2['default'].createElement(
      Component,
      _extends({}, this.props, {
        type: this.props.type || 'button',
        className: _classnames2['default'](this.props.className, classes) }),
      this.props.children
    );
  },

  renderNavItem: function renderNavItem(classes) {
    var liClasses = {
      active: this.props.active
    };

    return _react2['default'].createElement(
      'li',
      { className: _classnames2['default'](liClasses) },
      this.renderAnchor(classes)
    );
  }
});

exports['default'] = Button;
module.exports = exports['default'];


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Class org.apache.solr.handler.IndexFetcher.CompareResult (Solr 5.3.1 API)</title>
<meta name="date" content="2015-09-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.solr.handler.IndexFetcher.CompareResult

Packages that use IndexFetcher.CompareResult

Package
Description

org.apache.solr.handler

Concrete implementations of SolrRequestHandler

Uses of IndexFetcher.CompareResult in org.apache.solr.handler

Methods in org.apache.solr.handler that return IndexFetcher.CompareResult

Modifier and Type
Method and Description

protected static IndexFetcher.CompareResult
IndexFetcher.compareFile(Directory indexDir,
           Version version,
           String filename,
           Long backupIndexFileLen,
           Long backupIndexFileChecksum)

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

          Copyright © 2000-2015 Apache Software Foundation.  All Rights Reserved.


text:
itemName = "Weighted Companion Cube"

-- That variable is defined at the top level of a source file.


text:
package org.ovirt.engine.ui.webadmin.gin.uicommon;

import org.ovirt.engine.core.common.businessentities.AuditLog;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.Permissions;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.ui.common.presenter.AbstractModelBoundPopupPresenterWidget;
import org.ovirt.engine.ui.common.presenter.popup.DefaultConfirmationPopupPresenterWidget;
import org.ovirt.engine.ui.common.presenter.popup.RemoveConfirmationPopupPresenterWidget;
import org.ovirt.engine.ui.common.presenter.popup.RolePermissionsRemoveConfirmationPopupPresenterWidget;
import org.ovirt.engine.ui.common.uicommon.model.DetailModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.DetailTabModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.MainModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.MainTabModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailTabModelProvider;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateDiskListModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateEventListModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateGeneralModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateInterfaceListModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateListModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateStorageListModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateVmListModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.DiskModel;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.PermissionsPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.event.EventPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.quota.ChangeQuotaPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.storage.DisksAllocationPopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.template.TemplateInterfacePopupPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.template.TemplateNewPresenterWidget;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.vm.VmExportPopupPresenterWidget;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.inject.client.AbstractGinModule;
import com.google.inject.Provider;
import com.google.inject.Provides;
import com.google.inject.Singleton;

public class TemplateModule extends AbstractGinModule {

    // Main List Model

    @Provides
    @Singleton
    public MainModelProvider<VmTemplate, TemplateListModel> getTemplateListProvider(EventBus eventBus,
            Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
            final Provider<TemplateNewPresenterWidget> popupProvider,
            final Provider<VmExportPopupPresenterWidget> exportPopupProvider,
            final Provider<RemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
        return new MainTabModelProvider<VmTemplate, TemplateListModel>(eventBus, defaultConfirmPopupProvider, TemplateListModel.class) {
            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(TemplateListModel source,
                    UICommand lastExecutedCommand, Model windowModel) {
                TemplateListModel model = getModel();

                if (lastExecutedCommand == model.getEditCommand()) {
                    return popupProvider.get();
                } else if (lastExecutedCommand == getModel().getExportCommand()) {
                    return exportPopupProvider.get();
                } else {
                    return super.getModelPopup(source, lastExecutedCommand, windowModel);
                }
            }

            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(TemplateListModel source,
                    UICommand lastExecutedCommand) {
                if (lastExecutedCommand == getModel().getRemoveCommand()) {
                    return removeConfirmPopupProvider.get();
                } else {
                    return super.getConfirmModelPopup(source, lastExecutedCommand);
                }
            }
        };
    };

    // Form Detail Models

    @Provides
    @Singleton
    public DetailModelProvider<TemplateListModel, TemplateGeneralModel> getTemplateGeneralProvider(EventBus eventBus,
            Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider) {
        return new DetailTabModelProvider<TemplateListModel, TemplateGeneralModel>(
                eventBus, defaultConfirmPopupProvider,
                TemplateListModel.class,
                TemplateGeneralModel.class);
    }

    // Searchable Detail Models

    @Provides
    @Singleton
    public SearchableDetailModelProvider<Permissions, TemplateListModel, PermissionListModel> getPermissionListProvider(EventBus eventBus,
            Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
            final Provider<PermissionsPopupPresenterWidget> popupProvider,
            final Provider<RolePermissionsRemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
        return new SearchableDetailTabModelProvider<Permissions, TemplateListModel, PermissionListModel>(
                eventBus, defaultConfirmPopupProvider,
                TemplateListModel.class,
                PermissionListModel.class) {
            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(PermissionListModel source,
                    UICommand lastExecutedCommand, Model windowModel) {
                if (lastExecutedCommand == getModel().getAddCommand()) {
                    return popupProvider.get();
                } else {
                    return super.getModelPopup(source, lastExecutedCommand, windowModel);
                }
            }

            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(PermissionListModel source,
                    UICommand lastExecutedCommand) {
                if (lastExecutedCommand == getModel().getRemoveCommand()) {
                    return removeConfirmPopupProvider.get();
                } else {
                    return super.getConfirmModelPopup(source, lastExecutedCommand);
                }
            }
        };
    }

    @Provides
    @Singleton
    public SearchableDetailModelProvider<DiskModel, TemplateListModel, TemplateDiskListModel> getTemplateDiskListProvider(EventBus eventBus,
            Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
            final Provider<DisksAllocationPopupPresenterWidget> copyPopupProvider,
            final Provider<ChangeQuotaPopupPresenterWidget> changeQutoaPopupProvider) {
        return new SearchableDetailTabModelProvider<DiskModel, TemplateListModel, TemplateDiskListModel>(
                eventBus, defaultConfirmPopupProvider,
                TemplateListModel.class,
                TemplateDiskListModel.class) {
            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(TemplateDiskListModel source,
                    UICommand lastExecutedCommand,
                    Model windowModel) {
                if (lastExecutedCommand == getModel().getCopyCommand()) {
                    return copyPopupProvider.get();
                } else if (lastExecutedCommand == getModel().getChangeQuotaCommand()) {
                    return changeQutoaPopupProvider.get();
                } else {
                    return super.getModelPopup(source, lastExecutedCommand, windowModel);
                }
            }
        };
    }

    @Provides
    @Singleton
    public SearchableDetailModelProvider<VmNetworkInterface, TemplateListModel, TemplateInterfaceListModel> getTemplateInterfaceListProvider(EventBus eventBus,
            Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
            final Provider<TemplateInterfacePopupPresenterWidget> popupProvider,
            final Provider<RemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
        return new SearchableDetailTabModelProvider<VmNetworkInterface, TemplateListModel, TemplateInterfaceListModel>(
                eventBus, defaultConfirmPopupProvider,
                TemplateListModel.class,
                TemplateInterfaceListModel.class) {
            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(TemplateInterfaceListModel source,
                    UICommand lastExecutedCommand,
                    Model windowModel) {
                if ((lastExecutedCommand == getModel().getNewCommand())
                        || (lastExecutedCommand == getModel().getEditCommand())) {
                    return popupProvider.get();
                } else {
                    return super.getModelPopup(source, lastExecutedCommand, windowModel);
                }
            }

            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(TemplateInterfaceListModel source,
                    UICommand lastExecutedCommand) {
                if (lastExecutedCommand == getModel().getRemoveCommand()) {
                    return removeConfirmPopupProvider.get();
                } else {
                    return super.getConfirmModelPopup(source, lastExecutedCommand);
                }
            }
        };
    }

    @Provides
    @Singleton
    public SearchableDetailModelProvider<StorageDomain, TemplateListModel, TemplateStorageListModel> getTemplateStorageListProvider(EventBus eventBus,
            Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
            final Provider<RemoveConfirmationPopupPresenterWidget> removeConfirmPopupProvider) {
        return new SearchableDetailTabModelProvider<StorageDomain, TemplateListModel, TemplateStorageListModel>(
                eventBus, defaultConfirmPopupProvider,
                TemplateListModel.class,
                TemplateStorageListModel.class) {
            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends ConfirmationModel, ?> getConfirmModelPopup(TemplateStorageListModel source,
                    UICommand lastExecutedCommand) {
                if (lastExecutedCommand == getModel().getRemoveCommand()) {
                    return removeConfirmPopupProvider.get();
                } else {
                    return super.getConfirmModelPopup(source, lastExecutedCommand);
                }
            }
        };
    }

    @Provides
    @Singleton
    public SearchableDetailModelProvider<VM, TemplateListModel, TemplateVmListModel> getTemplateVmListProvider(EventBus eventBus,
            Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider) {
        return new SearchableDetailTabModelProvider<VM, TemplateListModel, TemplateVmListModel>(
                eventBus, defaultConfirmPopupProvider,
                TemplateListModel.class,
                TemplateVmListModel.class);
    }

    @Provides
    @Singleton
    public SearchableDetailModelProvider<AuditLog, TemplateListModel, TemplateEventListModel> getTemplateEventListProvider(EventBus eventBus,
            Provider<DefaultConfirmationPopupPresenterWidget> defaultConfirmPopupProvider,
            final Provider<EventPopupPresenterWidget> eventPopupProvider) {
        return new SearchableDetailTabModelProvider<AuditLog, TemplateListModel, TemplateEventListModel>(
                eventBus, defaultConfirmPopupProvider,
                TemplateListModel.class,
                TemplateEventListModel.class) {
            @Override
            public AbstractModelBoundPopupPresenterWidget<? extends Model, ?> getModelPopup(TemplateEventListModel source,
                    UICommand lastExecutedCommand,
                    Model windowModel) {
                if (lastExecutedCommand.equals(getModel().getDetailsCommand())) {
                    return eventPopupProvider.get();
                } else {
                    return super.getModelPopup(source, lastExecutedCommand, windowModel);
                }
            }
        };
    }

    @Override
    protected void configure() {
    }

}


text:
class Point_1D
{
public:
    Point_1D( double x ) ;
    double return_x() ;
    void   set_x(double x);
    int    return_centerID() ;

    void set_centerID( int ID ) ;
    bool idWasUnchanged() ;

protected:
    double x ;
    int centerID ;
    int previousCenterID ;

    int changeCount ;
};


text:
/*
 * Distanceable interface.
 */
#ifndef INTERFACES__DISTANCEABLE_HH
#define INTERFACES__DISTANCEABLE_HH

namespace interfaces {

/*
 * Template interface for distanceables.
 *
 * If class X extends distanceable<T,V>, then:
 * (1) X must be a T, and
 * (2) X must implement a distance function across type T
 *     that returns a value of type V.
 *
 * Note that the interface is the same regardless of T's const qualifier.
 */
template <typename T, typename V>
class distanceable {
public:
   /*
    * Destructor.
    */
   virtual ~distanceable();

   /*
    * Function for computing distance between two distanceable objects.
    */
   static V distance(const distanceable<T,V>&, const distanceable<T,V>&);

   /*
    * Method for computing distance to other distanceable<T,V> objects.
    * A distanceable<T,V> is cast to a T before calling distance_to.
    */
   V distance_to(const distanceable<T,V>&) const;

   /*
    * Virtual distance method.
    */
   virtual V distance_to(const T&) const = 0;
};

template <typename T, typename V>
class distanceable<const T,V> : public distanceable<T,V> { };

/*
 * Destructor.
 */
template <typename T, typename V>
distanceable<T,V>::~distanceable() { }

/*
 * Function for computing distance between two distanceable objects.
 */
template <typename T, typename V>
V distanceable<T,V>::distance(
   const distanceable<T,V>& t0,
   const distanceable<T,V>& t1)
{
   return (t0.distance_to(static_cast<const T&>(t1)));
}

/*
 * Method for computing distance to other distanceable<T,V> objects.
 * A distanceable<T,V> is cast to a T before calling distance_to.
 */
template <typename T, typename V>
V distanceable<T,V>::distance_to(const distanceable<T,V>& that) const {
   return (this->distance_to(static_cast<const T&>(that)));
}

} /* namespace interfaces */

#endif


text:
namespace TicTacToe.Web.DataModels
{
    using System;
    using System.Linq.Expressions;
    using TicTacToe.Models;

    public class GameInfoDataModel
    {
        public static Expression<Func<Game, GameInfoDataModel>> FromGame
        {
            get
            {
                return g => new GameInfoDataModel
                {
                    Id = g.Id,
                    Board = g.Board,
                    FirstPlayerName = g.FirstPlayer.UserName,
                    SecondPlayerName = g.SecondPlayer.UserName,
                    State = g.State
                };
            }
        }

        public Guid Id { get; set; }

        public string Board { get; set; }

        public string FirstPlayerName { get; set; }

        public string SecondPlayerName { get; set; }

        public GameState State { get; set; }
    }
}


text:
exports.play = function(ji) {
	var player = Ti.Media.createSound({url:"/assets/sounds/" + ji + '.mp3'});
	player.play();
}