text:
package edu.kit.dama.rest.client.setup;

import edu.kit.dama.rest.client.DataManagerPropertiesImpl;
import edu.kit.dama.rest.client.DataManagerPropertiesHelper;
import edu.kit.jcommander.generic.status.CommandStatus;
import edu.kit.jcommander.generic.status.Status;
import edu.kit.dama.mdm.base.Investigation;
import edu.kit.dama.mdm.base.MetaDataSchema;
import edu.kit.dama.mdm.base.OrganizationUnit;
import edu.kit.dama.mdm.base.Participant;
import edu.kit.dama.mdm.base.Relation;
import edu.kit.dama.mdm.base.Study;
import edu.kit.dama.mdm.base.Task;
import edu.kit.dama.mdm.base.UserData;
import edu.kit.dama.rest.SimpleRESTContext;
import edu.kit.dama.rest.admin.types.UserDataWrapper;
import edu.kit.dama.rest.basemetadata.client.impl.BaseMetaDataRestClient;
import edu.kit.dama.rest.basemetadata.types.InvestigationWrapper;
import edu.kit.dama.rest.basemetadata.types.MetadataSchemaWrapper;
import edu.kit.dama.rest.basemetadata.types.OrganizationUnitWrapper;
import edu.kit.dama.rest.basemetadata.types.StudyWrapper;
import edu.kit.dama.rest.basemetadata.types.TaskWrapper;
import edu.kit.dama.rest.client.AbstractGenericRestClient;
import edu.kit.dama.rest.mdm.base.client.InvestigationBuilder;
import edu.kit.dama.rest.mdm.base.client.MetadataSchemaBuilder;
import edu.kit.dama.rest.mdm.base.client.OrganizationUnitBuilder;
import edu.kit.dama.rest.mdm.base.client.TaskBuilder;
import edu.kit.dama.rest.mdm.base.client.UpdateInvestigation;
import edu.kit.dama.rest.mdm.base.client.UpdateOrganizationUnit;
import edu.kit.dama.rest.mdm.base.client.UpdateStudy;
import edu.kit.dama.util.StdIoUtils;
import java.io.PrintStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Generic class for generating base metadata for repository. All methods
 * require properly configured settings. To validate settings the following code
 * snippet may be used:
 *
 * @see AbstractGenericRestClient#testDataManagerSettings()  <pre>
 * {@code
 *   try {
 *     GenericAccessClient accessClient = new GenericAccessClient();
 *     DataManagerPropertiesImpl myProperties = accessClient.testDataManagerSettings();
 *   } catch (IllegalArgumentException iae) {
 *     iae.printStackTrace();
 *   }
 * }
 * </pre>
 *
 * @see DataManagerPropertiesHelper
 * @see edu.kit.dama.rest.client.DataManagerProperties
 * @author hartmann-v
 */
public class GenericSetupClient extends AbstractGenericRestClient {

  /**
   * Switch on/off verbosing output.
   */
  private static boolean verbose;

  /**
   * The logger
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(GenericSetupClient.class);

  /**
   * Placeholder if no suitable id is available. May also imply that a new
   * instance has to be created.
   */
  private static final long NO_ID = -1;

  /**
   * Placeholder for cancel operation.
   */
  private static final long CANCEL_ID = -2;

  /**
   * Output for query data.
   */
  private static final String DEFAULT = "If no input is given the default value printed in square brackets is choosen.";
  /**
   * Definition for agreement.
   */
  private static final String YES = "y".toLowerCase();
  /**
   * Definition for rejection.
   */
  private static final String NO = "n".toLowerCase();
  /**
   * Separator between sections.
   */
  private static final String LINE_SEPARATOR = "-------------------------------------------\n";

  /**
   * Switch on/off verbose output.
   *
   * @param aVerbose the verbose to set
   */
  public static void setVerbose(boolean aVerbose) {
    verbose = aVerbose;
  }

  /**
   * Rest client.
   */
  private BaseMetaDataRestClient bmdrc;
  /**
   * Properties for REST.
   */
  DataManagerPropertiesImpl properties = null;

  /**
   * Output to console.
   */
  private final PrintStream output = System.out;

  /**
   * Constructor. Only for internal usage.
   */
  protected GenericSetupClient() {
    initializeRest();
  }

  /**
   * Initialize Rest settings.
   */
  private void initializeRest() {
    try {
      properties = testDataManagerSettings();

      if (properties != null) {
        // <editor-fold defaultstate="collapsed" desc="Initialize REST">
        SimpleRESTContext context = new SimpleRESTContext(properties.getAccessKey(), properties.getAccessSecret());
        bmdrc = new BaseMetaDataRestClient(properties.getRestUrl() + REST_BASE_META_DATA_PATH, context);
      }
    } catch (IllegalArgumentException ex) {
      LOGGER.error(null, ex);
      returnStatus = new CommandStatus(ex);
    }
    LOGGER.info("ReturnValue (CommandStatus): " + returnStatus);
  }

  // <editor-fold defaultstate="collapsed" desc="Starting points for the jCommander commands.">
  /**
   * Execute command using jcommander. Parameters already parsed by JCommander.
   *
   * @param pStudy parsed arguments.
   * @param pInteractive query the parameters.
   * @return Status of the command.
   */
  public static CommandStatus executeCommand(Study pStudy, boolean pInteractive) {
    GenericSetupClient gac = new GenericSetupClient();

    return gac.createStudy(pStudy, pInteractive);
  }

  /**
   * Execute command using jcommander. Parameters already parsed by JCommander.
   *
   * @param pStudy parsed arguments.
   * @param pInteractive query the parameters.
   * @return Status of the command.
   */
  public static CommandStatus executeCommand(UpdateStudy pStudy, boolean pInteractive) {
    GenericSetupClient gac = new GenericSetupClient();

    return gac.updateStudy(pStudy.getStudyId(), pInteractive);
  }

  /**
   * Execute command using jcommander. Parameters already parsed by JCommander.
   *
   * @param pOrganizationUnit parsed arguments.
   * @param pInteractive query the parameters.
   * @return Status of the command.
   */
  public static CommandStatus executeCommand(UpdateOrganizationUnit pOrganizationUnit, boolean pInteractive) {
    GenericSetupClient gac = new GenericSetupClient();

    return gac.updateOrganizationUnit(pOrganizationUnit.getOrganizationUnitId(), pInteractive);
  }

  /**
   * Execute command using jcommander. Parameters already parsed by JCommander.
   *
   * @param pInvestigation parsed arguments.
   * @param pInteractive query the parameters.
   * @return Status of the command.
   */
  public static CommandStatus executeCommand(UpdateInvestigation pInvestigation, boolean pInteractive) {
    GenericSetupClient gac = new GenericSetupClient();

    return gac.updateInvestigation(pInvestigation.getInvestigationId(), pInteractive);
  }

  /**
   * Execute command using jcommander. Parameters already parsed by JCommander.
   *
   * @param pInvestigation parsed arguments.
   * @param pInteractive query the parameters.
   * @return Status of the command.
   */
  public static CommandStatus executeCommand(Investigation pInvestigation, boolean pInteractive) {
    GenericSetupClient gac = new GenericSetupClient();

    return gac.createInvestigation(pInvestigation, pInteractive);
  }

  /**
   * Execute command using jcommander. Parameters already parsed by JCommander.
   *
   * @param pOrganizationUnit parsed arguments.
   * @param pInteractive query the parameters.
   * @return Status of the command.
   */
  public static CommandStatus executeCommand(OrganizationUnit pOrganizationUnit, boolean pInteractive) {
    GenericSetupClient gac = new GenericSetupClient();

    return gac.createOrganizationUnit(pOrganizationUnit, pInteractive);
  }

  /**
   * Execute command using jcommander. Parameters already parsed by JCommander.
   *
   * @param pMetadataSchema parsed arguments.
   * @param pInteractive query the parameters.
   * @return Status of the command.
   */
  public static CommandStatus executeCommand(MetaDataSchema pMetadataSchema, boolean pInteractive) {
    GenericSetupClient gac = new GenericSetupClient();

    return gac.createMetadataSchema(pMetadataSchema, pInteractive);
  }

  /**
   * Execute command using jcommander. Parameters already parsed by JCommander.
   *
   * @param pTask parsed arguments.
   * @param pInteractive query the parameters.
   * @return Status of the command.
   */
  public static CommandStatus executeCommand(Task pTask, boolean pInteractive) {
    GenericSetupClient gac = new GenericSetupClient();

    return gac.createTask(pTask, pInteractive);
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="create... (Study, investigation, organization unit, metadata schema, task)">
  /**
   * Create a study.
   *
   * @param pStudy Study to create.
   * @param pInteractive Query the settings on command line.
   * @return Status of the command.
   */
  private CommandStatus createStudy(Study pStudy, boolean pInteractive) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    properties = testDataManagerSettings();
    if (pInteractive) {
      queryStudy(pStudy);
    }
    PrintUtil.printStudy(pStudy, true);
    if (queryYesNoAnswer("Do you want to write the study to the server?", NO)) {
      returnValue = writeStudy(pStudy);
    }
    returnStatus = returnValue;
    return getReturnStatus();
  }

  /**
   * Create an investigation.
   *
   * @param pInvestigation Investigation to create.
   * @param pInteractive Query the settings on command line.
   * @return Status of the command.
   */
  private CommandStatus createInvestigation(Investigation pInvestigation, boolean pInteractive) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    properties = testDataManagerSettings();
    if (pInteractive) {
      returnValue = queryInvestigation(pInvestigation, true);
    }
    PrintUtil.printInvestigation(pInvestigation, true);
    if (queryYesNoAnswer("Do you want to write the investigation to the server?", NO)) {
      Study selectStudy = pInvestigation.getStudy();
      if ((selectStudy == null) || (selectStudy.getStudyId() == null)) {
        selectStudy = selectStudy();
      }
      if (selectStudy != null) {
        returnValue = writeInvestigation(selectStudy.getStudyId(), pInvestigation);
      }
    }

    returnStatus = returnValue;
    return getReturnStatus();
  }

  /**
   * Create a metadata schema.
   *
   * @param pMetadataSchema Metadata schema to create.
   * @param pInteractive Query the settings on command line.
   * @return Status of the command.
   */
  private CommandStatus createMetadataSchema(MetaDataSchema pMetadataSchema, boolean pInteractive) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    properties = testDataManagerSettings();
    if (pInteractive) {
      returnValue = queryMetadataSchema(pMetadataSchema);
    }
    PrintUtil.printMetadataSchema(pMetadataSchema);
    if (queryYesNoAnswer("Do you want to write the metadata schema to the server?", NO)) {
      returnValue = writeMetadataSchema(null, pMetadataSchema);
    }
    returnStatus = returnValue;
    return getReturnStatus();
  }

  /**
   * Create an organization unit.
   *
   * @param pOrganizationUnit Organization unit to create.
   * @param pInteractive Query the settings on command line.
   * @return Status of the command.
   */
  private CommandStatus createOrganizationUnit(OrganizationUnit pOrganizationUnit, boolean pInteractive) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    properties = testDataManagerSettings();
    if (pInteractive) {
      returnValue = queryOrganizationUnit(pOrganizationUnit, false);
    }
    PrintUtil.printOrganizationUnit(pOrganizationUnit);
    if (queryYesNoAnswer("Do you want to write the organization unit to the server?", NO)) {
      returnValue = writeOrganizationUnit(pOrganizationUnit);
    }
    returnStatus = returnValue;
    return getReturnStatus();
  }

  /**
   * Create a task.
   *
   * @param pTask Task to create.
   * @param pInteractive Query the settings on command line.
   * @return Status of the command.
   */
  private CommandStatus createTask(Task pTask, boolean pInteractive) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    properties = testDataManagerSettings();
    if (pInteractive) {
      returnValue = queryTask(pTask);
    }
    PrintUtil.printTask(pTask);
    if (queryYesNoAnswer("Do you want to write the task to the server?", NO)) {
      returnValue = writeTask(pTask);
    }
    returnStatus = returnValue;
    return getReturnStatus();
  }

  // </editor-fold>
  // <editor-fold defaultstate="collapsed" desc="update ... (Study, investigation, organization unit)">
  /**
   * Update a study.
   *
   * @param pStudyId Study to update.
   * @param pInteractive Query the settings on command line.
   * @return Status of the command.
   */
  private CommandStatus updateStudy(Long pStudyId, boolean pInteractive) {
    CommandStatus returnValue;
    properties = testDataManagerSettings();
    Study study;
    Long studyId = pStudyId;
    if (pInteractive || (pStudyId == null)) {
      study = selectStudy();
    } else {
      study = bmdrc.getStudyById(studyId, properties.getUserGroup()).getEntities().get(0);
    }
    if (study == null) {
      return new CommandStatus(Status.FAILED);
    }
    if (study.getManager() != null) {
      study.setManager(bmdrc.getUserDataById(study.getManager().getUserId(), properties.getUserGroup()).getEntities().get(0));
    }
    returnValue = queryStudy(study);

    PrintUtil.printStudy(study, true);
    if (queryYesNoAnswer("Do you want to update the study?", NO)) {
      writeStudy(study);
    }

    returnStatus = returnValue;
    return getReturnStatus();
  }

  /**
   * Update an investigation.
   *
   * @param pInvestigationId Investigation to update.
   * @param pInteractive Query the settings on command line.
   * @return Status of the command.
   */
  private CommandStatus updateInvestigation(Long pInvestigationId, boolean pInteractive) {
    CommandStatus returnValue;
    properties = testDataManagerSettings();
    Investigation investigation;
    Long investigationId = pInvestigationId;
    if (pInteractive || (pInvestigationId == null)) {
      investigation = selectInvestigation(0l);
    } else {
      investigation = bmdrc.getInvestigationById(investigationId, properties.getUserGroup()).getEntities().get(0);
    }
    if (investigation == null) {
      return new CommandStatus(Status.FAILED);
    }
    returnValue = queryInvestigation(investigation, true);

    investigationId = investigation.getInvestigationId();
    PrintUtil.printInvestigation(investigation, true);
    if (queryYesNoAnswer("Do you want to update the investigation?", NO)) {
      output.println("Update investigation: ");
      bmdrc.updateInvestigation(investigationId, investigation, properties.getUserGroup());
      output.println("Update investigation: " + returnValue.getStatus());
      Set<MetaDataSchema> metaDataSchema = investigation.getMetaDataSchema();
      for (MetaDataSchema item : metaDataSchema) {
        if (item.getMetaDataSchemaUrl() != null) {
          writeMetadataSchema(investigationId, item);
        }
      }
      Set<Participant> participants = investigation.getParticipants();
      for (Participant item : participants) {
        if (item.getParticipantId() == null) {
          writeParticipants(investigationId, item);
        }
      }
    }
    returnStatus = returnValue;
    return getReturnStatus();
  }

  /**
   * Update an investigation.
   *
   * @param pOrganizationUnitId Investigation to update.
   * @param pInteractive Query the settings on command line.
   * @return Status of the command.
   */
  private CommandStatus updateOrganizationUnit(Long pOrganizationUnitId, boolean pInteractive) {
    CommandStatus returnValue;
    properties = testDataManagerSettings();
    OrganizationUnit organization;
    Long organizationId = pOrganizationUnitId;
    if (pInteractive || (pOrganizationUnitId == null)) {
      organization = selectOrganizationUnit();
    } else {
      organization = bmdrc.getOrganizationUnitById(organizationId, properties.getUserGroup()).getEntities().get(0);
      if (organization.getManager() != null) {
        organization.setManager(bmdrc.getUserDataById(organization.getManager().getUserId(), properties.getUserGroup()).getEntities().get(0));
      }
    }
    if (organization == null) {
      return new CommandStatus(Status.FAILED);
    }
    organizationId = organization.getOrganizationUnitId();
    returnValue = queryOrganizationUnit(organization, true);

    PrintUtil.printOrganizationUnit(organization);
    if (queryYesNoAnswer("Do you want to update the organization unit?", NO)) {
      SimpleRESTContext context = new SimpleRESTContext(properties.getAccessKey(), properties.getAccessSecret());
      output.println("Update organization unit: ");
      bmdrc.updateOrganizationUnit(organizationId, organization, properties.getUserGroup(), context);
      output.println("Update organization unit: " + returnValue.getStatus());
    }

    returnStatus = returnValue;
    return getReturnStatus();
  }

  // </editor-fold>
  // <editor-fold defaultstate="collapsed" desc="query... (Study, investigation, organization unit, metadata schema, task)">
  /**
   * Query values for study.
   *
   * @param pStudy Study holding preset values.
   * @return Status of the command.
   */
  private CommandStatus queryStudy(Study pStudy) {
    CommandStatus returnValue = new CommandStatus(Status.SUCCESSFUL);
    output.println("Please input the new values for the study\n" + DEFAULT);
    pStudy.setTopic(queryStringWithDefaultValue("Topic", pStudy.getTopic()));
    pStudy.setNote(queryStringWithDefaultValue("Note", pStudy.getNote()));
    pStudy.setLegalNote(queryStringWithDefaultValue("Legal note", pStudy.getLegalNote()));
    pStudy.setStartDate(queryDateWithDefaultValue("Start date", pStudy.getStartDate()));
    pStudy.setEndDate(queryDateWithDefaultValue("End date", pStudy.getEndDate()));
    UserData manager = pStudy.getManager();
    if (manager != null) {
      output.format("Actual manager: %s (%s) - %s", manager.getFullname(), manager.getDistinguishedName(), manager.getEmail());
    }
    if (queryYesNoAnswer("Do you want to select a (new) manager?", NO)) {
      UserData selectUser = selectUser();
      pStudy.setManager(selectUser);

    }
    while (queryYesNoAnswer("Do you want to add a relation to the study?", NO)) {
      // remove all existing relations in beforehand
      // Due to the test for duplicates during adding a relation this has
      // to be done to avoid loading of all relations via rest.
      // It's a ugly workaround but shouldn't matter in most cases.
      pStudy.setOrganizationUnits(new HashSet<Relation>());
      if (!addRelationToStudy(pStudy).getStatus().isSuccess()) {
        break;
      }
    }
    if (queryYesNoAnswer("Do you want to add an investigation to the study?", NO)) {
      addInvestigationToStudy(pStudy);
    }
    return returnValue;
  }

  /**
   * Query values for organization unit.
   *
   * @param pOrganizationUnit Organization unit holding preset values.
   * @param pUpdate For update manager can not be set any more.
   * @return Status of the command.
   */
  private CommandStatus queryOrganizationUnit(OrganizationUnit pOrganizationUnit, boolean pUpdate) {
    CommandStatus returnValue = new CommandStatus(Status.SUCCESSFUL);
    output.println("Please input the new values for the organization unit\n" + DEFAULT);
    pOrganizationUnit.setOuName(queryStringWithDefaultValue("OU name", pOrganizationUnit.getOuName()));
    pOrganizationUnit.setAddress(queryStringWithDefaultValue("Address", pOrganizationUnit.getAddress()));
    pOrganizationUnit.setCity(queryStringWithDefaultValue("City", pOrganizationUnit.getCity()));
    pOrganizationUnit.setZipCode(queryStringWithDefaultValue("Zipcode", pOrganizationUnit.getZipCode()));
    pOrganizationUnit.setCountry(queryStringWithDefaultValue("Country", pOrganizationUnit.getCountry()));
    pOrganizationUnit.setWebsite(queryStringWithDefaultValue("Website", pOrganizationUnit.getWebsite()));
    UserData ouManager;
    if (!pUpdate) {
      ouManager = pOrganizationUnit.getManager();
      if (ouManager != null) {
        output.format("Actual manager: %s (%s) - %s", ouManager.getFullname(), ouManager.getDistinguishedName(), ouManager.getEmail());
      }
      if (queryYesNoAnswer("Do you want to select a (new) manager?", NO)) {
        UserData selectUser = selectUser();
        pOrganizationUnit.setManager(selectUser);

      }
    }
    return returnValue;
  }

  /**
   * Query values for investigation.
   *
   * @param pInvestigation Investigation holding preset values.
   * @param pRecursive Recursive queries.
   * @return Status of the command.
   */
  private CommandStatus queryInvestigation(Investigation pInvestigation, boolean pRecursive) {
    CommandStatus returnValue = new CommandStatus(Status.SUCCESSFUL);
    output.println("Please input the new values for the investigation\n" + DEFAULT);
    pInvestigation.setTopic(queryStringWithDefaultValue("Topic", pInvestigation.getTopic()));
    pInvestigation.setNote(queryStringWithDefaultValue("Note", pInvestigation.getNote()));
    pInvestigation.setDescription(queryStringWithDefaultValue("Description", pInvestigation.getDescription()));
    pInvestigation.setStartDate(queryDateWithDefaultValue("Start date", pInvestigation.getStartDate()));
    pInvestigation.setEndDate(queryDateWithDefaultValue("End date", pInvestigation.getEndDate()));
    if (pRecursive) {
      while (queryYesNoAnswer("Would you like to add a metadata schema to investigation?", NO)) {
        if (!addMetadataSchemaToInvestigation(pInvestigation).getStatus().isSuccess()) {
          break;
        }
      }
      while (queryYesNoAnswer("Would you like to add a participant to investigation?", NO)) {
        if (!addParticipantToInvestigation(pInvestigation).getStatus().isSuccess()) {
          break;
        }
      }
    }
    return returnValue;
  }

  /**
   * Query for a new metadata schema.
   *
   * @param pMetadataSchema Instance with preset values.
   * @return Status of the command.
   */
  private CommandStatus queryMetadataSchema(MetaDataSchema pMetadataSchema) {
    CommandStatus returnValue = new CommandStatus(Status.SUCCESSFUL);
    output.println("Please input the new value for metadata schema");
    pMetadataSchema.setMetaDataSchemaUrl(queryStringWithDefaultValue("Metadata schema URL", pMetadataSchema.getMetaDataSchemaUrl()));
    pMetadataSchema.setSchemaIdentifier(queryStringWithDefaultValue("Metadata schema identifier", pMetadataSchema.getSchemaIdentifier()));
    pMetadataSchema.setNamespace(queryStringWithDefaultValue("Namespace for schema", pMetadataSchema.getNamespace()));

    return returnValue;
  }

  /**
   * Query for a new task.
   *
   * @param pTask Instance with preset values.
   * @return Status of the command.
   */
  private CommandStatus queryTask(Task pTask) {
    CommandStatus returnValue = new CommandStatus(Status.SUCCESSFUL);
    output.println("Please input a new task");
    pTask.setTask(queryStringWithDefaultValue("Label", pTask.getTask()));

    return returnValue;
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="add... (Relation, Participant, MetadataSchema, Investigation)">
  /**
   * Add metadata schema to investigation.
   *
   * @param pInvestigation Investigation which should contain the (new) metadata
   * schema.
   * @return Status of the command.
   */
  private CommandStatus addMetadataSchemaToInvestigation(Investigation pInvestigation) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    // lookup for all defined metadata schemas.
    List<Long> ids = new ArrayList<>();
    List<String> descriptions = new ArrayList<>();
    // add one item for new metadata schema
    MetadataSchemaWrapper allMetadataSchemas = bmdrc.getAllMetadataSchemas(0, 100, properties.getUserGroup());
    for (MetaDataSchema item : allMetadataSchemas.getEntities()) {
      MetaDataSchema buffer = bmdrc.getMetadataSchemaById(item.getId(), properties.getUserGroup()).getEntities().get(0);
      ids.add(buffer.getId());
      descriptions.add(buffer.getSchemaIdentifier() + " -> " + buffer.getMetaDataSchemaUrl());
    }
    output.println("Please select a metadata schema!");
    Long selectedId = queryFromList(ids, descriptions, true);
    MetaDataSchema mds = new MetadataSchemaBuilder().build();
    switch (selectedId.intValue()) {
      case (int) NO_ID:
        returnValue = queryMetadataSchema(mds);
        break;
      case (int) CANCEL_ID:
        returnValue = new CommandStatus(Status.FAILED);
        break;
      default:
        // add selected Id to investigation.
        // read id from server
        mds = bmdrc.getMetadataSchemaById(selectedId, properties.getUserGroup()).getEntities().get(0);
    }
    pInvestigation.addMetaDataSchema(mds);
    return returnValue;
  }

  /**
   * Add an investigation to an existing study.
   *
   * @param pStudy Study which should contain the (new) investigation
   * @return command status
   */
  private CommandStatus addInvestigationToStudy(Study pStudy) {
    CommandStatus returnValue = new CommandStatus(Status.SUCCESSFUL);
    Investigation investigation = new InvestigationBuilder().build();
    CommandStatus status = queryInvestigation(investigation, true);
    if (status.getStatus().isSuccess()) {
      pStudy.addInvestigation(investigation);
    } else {
      returnValue = new CommandStatus(Status.FAILED);
    }
    return returnValue;
  }

  /**
   * Add a participant to an existing investigation.
   *
   * @param pInvestigation Investigation which should contain the participant.
   * @return command status
   */
  private CommandStatus addParticipantToInvestigation(Investigation pInvestigation) {
    CommandStatus returnValue = new CommandStatus(Status.SUCCESSFUL);
    UserData user = selectUser();
    Task task = selectTask();
    if ((task != null) && (user != null)) {
      Participant participant = new Participant(user, task);
      pInvestigation.addParticipant(participant);
    } else {
      returnValue = new CommandStatus(Status.FAILED);
    }
    return returnValue;
  }

  /**
   * Add a relation to an existing study.
   *
   * @param pStudy Study which should contain the relation.
   * @return command status
   */
  private CommandStatus addRelationToStudy(Study pStudy) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    OrganizationUnit organization = selectOrganizationUnit();
    if (organization != null) {
      Task task = selectTask();
      Relation relation = new Relation(organization, task);
      pStudy.addRelation(relation);
      returnValue = new CommandStatus(Status.SUCCESSFUL);
    }
    return returnValue;
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="select... (User, Task, OrganizationUnit)">
  /**
   * Select a study.
   *
   * @return Study (null if canceled)
   */
  private Study selectStudy() {
    Study returnValue = null;
    // lookup for all defined metadata schemas.
    List<Long> ids = new ArrayList<>();
    List<String> descriptions = new ArrayList<>();
    // add one item for new metadata schema
    StudyWrapper studies = bmdrc.getAllStudies(0, 100, properties.getUserGroup());
    for (Study item : studies.getEntities()) {
      Study buffer = bmdrc.getStudyById(item.getStudyId(), properties.getUserGroup()).getEntities().get(0);
      ids.add(buffer.getStudyId());
      descriptions.add(buffer.getTopic());
    }
    output.println("Please select a study!");
    Long selectedId = queryFromList(ids, descriptions, false);
    switch (selectedId.intValue()) {
      case (int) NO_ID:
      case (int) CANCEL_ID:
        break;
      default:
        // add selected Id to investigation.
        // read id from server
        returnValue = bmdrc.getStudyById(selectedId, properties.getUserGroup()).getEntities().get(0);
    }
    return returnValue;
  }

  /**
   * Select a investigation of a study.
   *
   * @return investigation (null if canceled)
   */
  private Investigation selectInvestigation(Long pStudyId) {
    Investigation returnValue = null;
    // lookup for all defined metadata schemas.
    List<Long> ids = new ArrayList<>();
    List<String> descriptions = new ArrayList<>();
    // add one item for new metadata schema
    InvestigationWrapper investigations = bmdrc.getAllInvestigations(pStudyId, 0, 100, properties.getUserGroup());
    for (Investigation item : investigations.getEntities()) {
      Investigation buffer = bmdrc.getInvestigationById(item.getInvestigationId(), properties.getUserGroup()).getEntities().get(0);
      ids.add(buffer.getInvestigationId());
      descriptions.add(buffer.getTopic());
    }
    output.println("Please select an investigation!");
    Long selectedId = queryFromList(ids, descriptions, false);
    switch (selectedId.intValue()) {
      case (int) NO_ID:
      case (int) CANCEL_ID:
        break;
      default:
        // add selected Id to investigation.
        // read id from server
        returnValue = bmdrc.getInvestigationById(selectedId, properties.getUserGroup()).getEntities().get(0);
        PrintUtil.printInvestigation(returnValue, true);
    }
    return returnValue;
  }

  /**
   * Select or create a new organization unit.
   *
   * @return organization unit (null if canceled)
   */
  private OrganizationUnit selectOrganizationUnit() {
    OrganizationUnit returnValue = null;
    // lookup for all defined metadata schemas.
    List<Long> ids = new ArrayList<>();
    List<String> descriptions = new ArrayList<>();
    // add one item for new metadata schema
    OrganizationUnitWrapper tasks = bmdrc.getAllOrganizationUnits(0, 100, properties.getUserGroup());
    for (OrganizationUnit item : tasks.getEntities()) {
      OrganizationUnit buffer = bmdrc.getOrganizationUnitById(item.getOrganizationUnitId(), properties.getUserGroup()).getEntities().get(0);
      ids.add(buffer.getOrganizationUnitId());
      descriptions.add(String.format("%s %s (%s)", buffer.getOuName(), buffer.getCity(), buffer.getCountry()));
    }
    output.println("Please select an organization unit!");
    Long selectedId = queryFromList(ids, descriptions, true);
    switch (selectedId.intValue()) {
      case (int) NO_ID:
        OrganizationUnit organization = new OrganizationUnitBuilder().build();
        queryOrganizationUnit(organization, false);
        returnValue = organization;
        break;
      case (int) CANCEL_ID:
        break;
      default:
        // add selected Id to investigation.
        // read id from server
        returnValue = bmdrc.getOrganizationUnitById(selectedId, properties.getUserGroup()).getEntities().get(0);
    }
    return returnValue;
  }

  /**
   * Select or create a new task.
   *
   * @return task (null if canceled)
   */
  private Task selectTask() {
    Task returnValue = null;
    // lookup for all defined metadata schemas.
    List<Long> ids = new ArrayList<>();
    List<String> descriptions = new ArrayList<>();
    // add one item for new metadata schema
    TaskWrapper tasks = bmdrc.getAllTasks(0, 100, properties.getUserGroup());
    for (Task item : tasks.getEntities()) {
      Task buffer = bmdrc.getTaskById(item.getTaskId(), properties.getUserGroup()).getEntities().get(0);
      ids.add(buffer.getTaskId());
      descriptions.add(buffer.getTask());
    }
    output.println("Please select a task!");
    Long selectedId = queryFromList(ids, descriptions, true);
    switch (selectedId.intValue()) {
      case (int) NO_ID:
        Task task = new TaskBuilder().build();
        queryTask(task);
        returnValue = task;
        break;
      case (int) CANCEL_ID:
        break;
      default:
        // add selected Id to investigation.
        // read id from server
        returnValue = bmdrc.getTaskById(selectedId, properties.getUserGroup()).getEntities().get(0);
    }
    return returnValue;
  }

  /**
   * Select a user.
   *
   * @return user (null if canceled)
   */
  private UserData selectUser() {
    UserData returnValue = null;
    // lookup for all defined metadata schemas.
    List<Long> ids = new ArrayList<>();
    List<String> descriptions = new ArrayList<>();
    // add one item for new metadata schema
    UserDataWrapper allUserData = bmdrc.getAllUserData(0, 100, properties.getUserGroup());
    for (UserData item : allUserData.getEntities()) {
      UserData buffer = bmdrc.getUserDataById(item.getUserId(), properties.getUserGroup()).getEntities().get(0);
      ids.add(buffer.getUserId());
      descriptions.add(buffer.getDistinguishedName() + " -> " + buffer.getEmail());
    }
    output.println("Please select an user!");
    Long selectedId = queryFromList(ids, descriptions, false);
    switch (selectedId.intValue()) {
      case (int) CANCEL_ID:
        break;
      default:
        // add selected Id to investigation.
        // read id from server
        returnValue = bmdrc.getUserDataById(selectedId, properties.getUserGroup()).getEntities().get(0);
    }
    return returnValue;
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc="Write instances">
  /**
   * Write a study to server.
   *
   * @param pStudy Study to write.
   * @return Status of the command.
   */
  private CommandStatus writeStudy(Study pStudy) {
    CommandStatus returnValue = new CommandStatus(Status.SUCCESSFUL);
    if (pStudy.getStudyId() == null) {
      output.println("Write study: ");
      if (verbose) {
        PrintUtil.printStudy(pStudy, true);
      }
      Study dummy = bmdrc.addStudy(pStudy, properties.getUserGroup()).getEntities().get(0);
      pStudy.setStudyId(dummy.getStudyId());
      output.println("Write study: " + returnValue.getStatus());
    } else {
      // As study already exists do an update.
      output.println("Update study: ");
      bmdrc.updateStudy(pStudy.getStudyId(), pStudy, properties.getUserGroup());
      output.println("Update study: " + returnValue.getStatus());
    }
    // Write investigations. Only new investigations are written to the server.
    Set<Investigation> investigations = pStudy.getInvestigations();
    if (investigations != null) {
      Iterator<Investigation> iterator = investigations.iterator();
      while (iterator.hasNext()) {
        returnValue = writeInvestigation(pStudy.getStudyId(), iterator.next());
      }
    }
    // Write relations. Only new relations are written to server.
    Set<Relation> relations = pStudy.getOrganizationUnits();
    if (relations != null) {
      Iterator<Relation> iterator = relations.iterator();
      while (iterator.hasNext()) {
        returnValue = writeRelation(pStudy.getStudyId(), iterator.next());
      }
    }
    return returnValue;
  }

  /**
   * Write an investigation to server.
   *
   * @param pStudyId Study containing investigation.
   * @param pInvestigation Investigation to write.
   * @return Status of the command.
   */
  private CommandStatus writeInvestigation(Long pStudyId, Investigation pInvestigation) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    if (pInvestigation.getInvestigationId() == null) {
      // investigation is not known to the server yet.
      if (pStudyId == null) {
        output.println("Select study to add investigation into:");
        Study selectStudy = selectStudy();
        if (selectStudy != null) {
          pStudyId = selectStudy.getStudyId();
        }
      }
      if (pStudyId != null) {
        output.println("Add investigation to study: ");
        if (verbose) {
          PrintUtil.printInvestigation(pInvestigation, false);
        }
        Investigation investigation = bmdrc.addInvestigationToStudy(pStudyId, pInvestigation, properties.getUserGroup()).getEntities().get(0);
        if (investigation != null) {
          returnValue = new CommandStatus(Status.SUCCESSFUL);
          pInvestigation.setInvestigationId(investigation.getInvestigationId());
          output.println("Add investigation to study: " + returnValue.getStatus());
        }
      } else {
        returnValue = new CommandStatus(Status.FAILED);
      }
    }
    Set<Participant> participants = pInvestigation.getParticipants();
    if (participants != null) {
      Iterator<Participant> iterator = participants.iterator();
      while (iterator.hasNext()) {
        returnValue = writeParticipants(pInvestigation.getInvestigationId(), iterator.next());
      }
    }
    Set<MetaDataSchema> metadataschema = pInvestigation.getMetaDataSchema();
    if (metadataschema != null) {
      Iterator<MetaDataSchema> iterator_1 = metadataschema.iterator();
      while (iterator_1.hasNext()) {
        returnValue = writeMetadataSchema(pInvestigation.getInvestigationId(), iterator_1.next());
      }
    }
    return returnValue;
  }

  /**
   * Write an relation to server.
   *
   * @param pStudyId Study containing relation.
   * @param pRelation Relation to write.
   * @return Status of the command.
   */
  private CommandStatus writeRelation(Long pStudyId, Relation pRelation) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    if (pRelation.getRelationId() == null) {
      // relation is not known to the server yet.
      if (pStudyId == null) {
        output.println("Select study to add relation into:");
        Study selectStudy = selectStudy();
        if (selectStudy != null) {
          pStudyId = selectStudy.getStudyId();
        }
      }
      if ((pStudyId != null) && (pRelation.getRelationId() == null)) {
        OrganizationUnit organization = pRelation.getOrganizationUnit();
        Task task = pRelation.getTask();
        if (organization != null) {
          if (organization.getOrganizationUnitId() == null) {
            writeOrganizationUnit(organization);
          }
          if (task != null) {
            if (task.getTaskId() == null) {
              writeTask(task);
            }
          }
          output.println("Add relation to study: ");
          if (verbose) {
            PrintUtil.printRelation(pRelation);
          }
          // method return Study wrapper which may already contain one or more relations!?
          StudyWrapper addRelationToStudy = bmdrc.addRelationToStudy(pStudyId, pRelation, properties.getUserGroup());
          if (addRelationToStudy != null) {
            returnValue = new CommandStatus(Status.SUCCESSFUL);
            output.println("New no of Relations: " + addRelationToStudy.getEntities().get(0).getOrganizationUnits().size());
            output.println("Add relation to study: finished");
          }
        }
      }
    }
    return returnValue;
  }

  /**
   * Write an participant to server.
   *
   * @param pInvestigationId Investigation containing participant.
   * @param pParticipant Participant to write.
   * @return Status of the command.
   */
  private CommandStatus writeParticipants(Long pInvestigationId, Participant pParticipant) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    if (pParticipant.getParticipantId() == null) {
      // relation is not known to the server yet.
      if (pInvestigationId == null) {
        output.println("Select investigation to add participant into:");
        output.println("First you have to select a study:");
        Long studyId = null;
        Study selectStudy = selectStudy();
        if (selectStudy != null) {
          studyId = selectStudy.getStudyId();
        }
        if (studyId != null) {
          output.println("Now you have to select a study:");
          pInvestigationId = selectInvestigation(studyId).getInvestigationId();
        }
      }
      if (pInvestigationId != null) {
        UserData user = pParticipant.getUser();
        Task task = pParticipant.getTask();
        if (user != null) {
          if (task != null) {
            if (task.getTaskId() == null) {
              writeTask(task);
            }
          }
          output.println("Add participant to investigation: ");
          if (verbose) {
            PrintUtil.printParticipant(pParticipant);
          }
          // method return investigation wrapper which may already contain one or more participants!?
          InvestigationWrapper addParticipantToInvestigation = bmdrc.addParticipantToInvestigation(pInvestigationId, pParticipant, properties.getUserGroup());
          if (addParticipantToInvestigation != null) {
            returnValue = new CommandStatus(Status.SUCCESSFUL);
            output.println("New no of participants: " + addParticipantToInvestigation.getEntities().get(0).getParticipants().size());
            output.println("Add participant to investigation: " + returnValue.getStatus());
          }
        }
      }
    }
    return returnValue;
  }

  /**
   * Write a organization unit to server.
   *
   * @param pOrganizationUnit organization unit to write.
   * @return Status of the command.
   */
  private CommandStatus writeOrganizationUnit(OrganizationUnit pOrganizationUnit) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    if (pOrganizationUnit.getOrganizationUnitId() == null) {
      output.println("Write organization unit: ");
      if (verbose) {
        PrintUtil.printOrganizationUnit(pOrganizationUnit);
      }
      OrganizationUnit oUnit = bmdrc.addOrganizationUnit(pOrganizationUnit, properties.getUserGroup()).getEntities().get(0);
      if (oUnit != null) {
        returnValue = new CommandStatus(Status.SUCCESSFUL);
        pOrganizationUnit.setOrganizationUnitId(oUnit.getOrganizationUnitId());
        output.println("Write organization unit: " + returnValue.getStatus());
      }
    }
    return returnValue;
  }

  /**
   * Write a task to server.
   *
   * @param pTask task unit to write.
   * @return Status of the command.
   */
  private CommandStatus writeTask(Task pTask) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    if (pTask.getTaskId() == null) {
      output.println("Write task: ");
      if (verbose) {
        PrintUtil.printTask(pTask);
      }
      Task task = bmdrc.addTask(pTask, properties.getUserGroup()).getEntities().get(0);
      if (task != null) {
        returnValue = new CommandStatus(Status.SUCCESSFUL);
        pTask.setTaskId(task.getTaskId());
        output.println("Write task: " + returnValue.getStatus());
      }
    }
    return returnValue;
  }

  /**
   * Write meta data schema to server.
   *
   * @param pInvestigationId id of the investigation.
   * @param pMetadataSchema meta data schema to write.
   * @return Status of the command.
   */
  private CommandStatus writeMetadataSchema(Long pInvestigationId, MetaDataSchema pMetadataSchema) {
    CommandStatus returnValue = new CommandStatus(Status.FAILED);
    if (pMetadataSchema.getId() == null) {
      output.println("Write metadata schema: ");
      if (verbose) {
        PrintUtil.printMetadataSchema(pMetadataSchema);
      }
      MetaDataSchema mds = bmdrc.addMetadataSchema(pMetadataSchema, properties.getUserGroup()).getEntities().get(0);
      if (mds != null) {
        returnValue = new CommandStatus(Status.SUCCESSFUL);
        pMetadataSchema.setId(mds.getId());
        output.println("Write metadata schema: " + returnValue.getStatus());
      }
    }
    if ((pInvestigationId != null) && (pMetadataSchema.getId() != null)) {
      output.println("Add metadata schema to investigation: ");
      if (verbose) {
        PrintUtil.printMetadataSchema(pMetadataSchema);
      }
      InvestigationWrapper addMetadataSchemaToInvestigation = bmdrc.addMetadataSchemaToInvestigation(pInvestigationId, pMetadataSchema, properties.getUserGroup());
      if (addMetadataSchemaToInvestigation != null) {
        returnValue = new CommandStatus(Status.SUCCESSFUL);
        output.println("No of new metadata schemas: " + addMetadataSchemaToInvestigation.getEntities().get(0).getMetaDataSchema().size());
        output.println("Add metadata schema to investigation: " + returnValue.getStatus());
      }
    }
    return returnValue;
  }

  // </editor-fold>
  // <editor-fold defaultstate="collapsed" desc="Helper methods for querying commandline.">
  /**
   * Query for a key. Default value may be available.
   *
   * @param pKey Key of the value.
   * @param pValue Old/default value.
   * @return new value.
   */
  private String queryStringWithDefaultValue(String pKey, String pValue) {
    output.format("%s [%s]:\n", pKey, pValue);
    return StdIoUtils.readStdInput(pValue);

  }

  /**
   * Query for a date with format: yyyy-MM-dd (e.g.: 2015-01-29)
   *
   * @param pKey Key of the value.
   * @param pValue Old/default value.
   * @return new value.
   */
  private Date queryDateWithDefaultValue(String pKey, Date pValue) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    if (pValue == null) {
      pValue = new Date();
    }
    String date = queryStringWithDefaultValue(pKey, sdf.format(pValue));
    Date newDate = null;
    try {
      newDate = sdf.parse(date);
    } catch (ParseException ex) {
      LOGGER.error(null, ex);
    }
    return newDate;
  }

  /**
   * Query for yes or no.
   *
   * @param pQuestion Question
   * @param pDefault YES or NO {@link #YES}, {@link #NO}
   * @return true if yes.
   */
  private boolean queryYesNoAnswer(String pQuestion, String pDefault) {
    String defaultAnswer = pDefault;
    output.print(LINE_SEPARATOR);
    output.format("\n%s (%s/%s)[%s]\n", pQuestion, YES, NO, defaultAnswer);
    String inputValue = StdIoUtils.readStdInput(defaultAnswer);

    return inputValue.toLowerCase().contains(YES);
  }

  @Override
  protected void checkArguments() {
    // do nothing at the moment as arguments already checked by jCommander
  }

  /**
   * If there is a limited number of possibility it has to be chosen from the
   * given list via the appropriate number.
   *
   * @param pProperty actualValue.
   * @param pPossibleValues list of values. NULL if any value is allowed.
   * @param pDescriptions list of descriptions. NULL if no description
   * @param pAllowCreation are new instances allowed or not. available.
   * @return id of the selected instance ({@link #NO_ID} = create new instance,
   * {@link #CANCEL_ID} = cancel operation)
   */
  private Long queryFromList(final List<Long> pPossibleValues, final List<String> pDescriptions, boolean pAllowCreation) {
    Long actualValue = CANCEL_ID;
    String formatString = "%3d: %4d ";
    String description = "- %s ";
    String marker = "*";
    int oldIndex = 1;
    if (pAllowCreation) {
      pPossibleValues.add(NO_ID);
      if (oldIndex <= 0) {
        oldIndex = pPossibleValues.size();
      }
      pDescriptions.add("+++ Create new instance. +++");
    }
    pPossibleValues.add(CANCEL_ID);
    pDescriptions.add("--- Cancel ---");

    int index = 1;
    output.println("Please choose via given index.");
    for (int pVIndex = 0; pVIndex < pPossibleValues.size(); pVIndex++) {
      String adaptedFormatString = formatString;
      if (pDescriptions.get(pVIndex) != null) {
        adaptedFormatString = adaptedFormatString + description;
      }
      if (oldIndex == index) {
        adaptedFormatString = marker + adaptedFormatString + marker;
      }
      output.println(String.format(adaptedFormatString, index++, pPossibleValues.get(pVIndex), pDescriptions.get(pVIndex)));
    }

    index = StdIoUtils.readIntFromStdInput(index, oldIndex) - 1;
    if (index < pPossibleValues.size()) {
      actualValue = pPossibleValues.get(index);
    }

    return actualValue;
  }
  // </editor-fold>

}


text:
"use strict";
var Boplex = {};

(function(Boplex){

  var _version = "0.0.3";

  function getFuncName(f){
    var funcNameRegex = /function (.{1,})\(/;
    var results = (funcNameRegex).exec(f);
    return (results && results.length > 1) ? results[1] : "";
  }

  function include(x, child, className){
    x[className] = child;
  }

  function inherit(child, parent){
    child.prototype = Object.create(parent.prototype);
    child.prototype.constructor = child;
    return child;
  }

  function getLogTime(currentdate){
    currentdate = currentdate || (new Date());
    var datetime = currentdate.getFullYear() +
      "." + (currentdate.getMonth()+1)  +
      "." + currentdate.getDate() +
      "_" + currentdate.getHours() +
      ":" + currentdate.getMinutes() +
      ":" + currentdate.getSeconds();
    return datetime;
  }

  function defineConstProp(x, propName, propVal){
    Object.defineProperty(x, propName, {
      writable: false,
      value: propVal,
    });
  }

  function random(a, b){
    return a + Math.round(Math.random()*(b - a));
  }

  function publish(x){
    x.getFuncName = getFuncName;
    x.defineConstProp = defineConstProp;
    x.include = include;
    x.inherit = inherit;
    x.getLogTime = getLogTime;
    x.random = random;
  }

  defineConstProp(Boplex, "Version", _version);
  publish(Boplex);

})(Boplex);

(function(target){
  "use strict";

  function BaseObject() {
    "obsolete";
  }

  function publish(x){
    x.BaseObject = BaseObject;
  }

  publish(target);

})(Boplex);

(function(Boplex){
  "use strict";

  function Logger(name){
    var _name = name;

    Logger.prototype.log = function(txt){
      console.log(Boplex.getLogTime() + " " + _name + " " + txt);
    };
  }

  function publish(x){
    x.Logger = Logger;
  }

  publish(Boplex);

})(Boplex);

(function(Boplex){
  "use strict";

  function Event(context, handler){
    var _context = context;
    var _handler = handler;

    Event.prototype.raise = function (args) {
      if (!_handler){
        return;
      }
      _handler(_context, args);
    };
  }

  function publish(x){
    x.Event = Event;
  }

  publish(Boplex);

})(Boplex);

"use strict";
var boplexTest = {};
(function(boplexTest){

  boplexTest.Version = "0.0.3";

})(boplexTest);

(function(boplexTest){
  "use strict";

  function Point(name, x, y, onMoved) {
    Boplex.BaseObject.call(this);
    var _logger = new Boplex.Logger("boplexTest.Point");
    this.name = name;
    var _x = x;
    var _y = y;
    var _onMoved = onMoved;

    function _getName(t){
      return t.name;
    }

    Point.prototype.getName = function(){
      return _getName.call(this, this);
    };

    Point.prototype.getPosition = function(){
      return {x: _x, y: _y};
    };

    Point.prototype.setPosition = function(pos){
      _logger.log("x:" + _x + ", y: " + _y);
      _x = pos.x;
      _y = pos.y;
      (new Boplex.Event(this, _onMoved)).raise(pos);
      _logger.log("x:" + _x + ", y: " + _y);
    };
  }
  boplexTest.Point = Boplex.inherit(Point, Object);

})(boplexTest);

console.log("Boplex Version: " + Boplex.Version);

boplexTest.Point.prototype.className = "boplexTest.Point";
var pt = new boplexTest.Point("A", 3, Boplex.random(0, 5), function(pt, pos){
  console.log("Point \"" + pt.getName() + "\" has been moved to:");
  console.dir(pos);
});

console.log(pt.className);
console.log("Point \"" + pt.getName() + "\" is located at:");
console.dir(pt.getPosition());
pt.setPosition({x: 4, y: 5});

console.log(boplexTest.Point.prototype);
console.dir(boplexTest.Point.prototype);

redpajama_set_name: RedPajamaGithub


text:
package com.quizup.core.activities;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;
import com.quizup.core.QuizApplication;
import com.quizup.lib.widgets.profilePicture.ProfilePicture;
import java.lang.reflect.Field;
import java.util.Map;
import o.ȉ;
import o.ȓ;
import o.Ί.1;
import o.Ꮀ.Ɩ;
import o.ᒫ;
import o.ᓑ;
import o.ᖟ;
import o.ᴧ;
import o.ṛ;
import o.ὶ;
import o.Ί;
import o.‿;
import o.‿.if;
import o.ⅹ;
import o.〵;
import o.ךּ;
import o.ﭠ;
import o.ﺩ;
import o.ﻟ;

public class ActivityNotificationHelper
{
  private static final int CHAT_DISMISS_DURATION = 10000;
  public static final String LOGTAG = ActivityNotificationHelper.class.getSimpleName();
  private Activity activity;
  protected DialogEventListener addFriendListener = new DialogEventListener()
  {
    public void leftButtonPressed()
    {
      Ί localΊ = new Ί(ActivityNotificationHelper.this.notificationPlayer);
      ⅹ localⅹ = QuizApplication.ˊ.ˋ;
      ᖟ localᖟ = new ᖟ(ActivityNotificationHelper.this.receiver, localⅹ, localΊ);
      String[] arrayOfString = new String[1];
      arrayOfString[0] = ActivityNotificationHelper.this.notificationPlayer.ˊ;
      localᖟ.execute(arrayOfString);
      〵.ˋ("Friend");
    }

    public void rightButtonPressed()
    {
      Intent localIntent = new Intent(ActivityNotificationHelper.this.activity, ProfileActivity.class);
      localIntent.putExtra("player_id", ActivityNotificationHelper.this.notificationPlayer.ˊ);
      ActivityNotificationHelper.this.activity.startActivity(localIntent);
    }
  };
  protected DialogEventListener challengeCompleteListener = new DialogEventListener()
  {
    public void leftButtonPressed()
    {
      EndGameActivity.startEndGameActivity(ActivityNotificationHelper.this.activity, ActivityNotificationHelper.this.notificationGameId, true);
      ActivityNotificationHelper.this.activity.overridePendingTransition(2130968581, 2130968583);
    }

    public void rightButtonPressed()
    {
      ActivityNotificationHelper.this.runMatchUpScene();
      Object localObject = Ꮀ.Ɩ.ィ("o.Ⅼ").getField("ʻ").get(null);
      Ꮀ.Ɩ.ィ("o.Ⅼ").getField("ﹳ").set(null, localObject);
    }
  };
  protected DialogEventListener challengeNudgeListener = new DialogEventListener()
  {
    public void dialogClosed()
    {
    }

    // ERROR //
    public void leftButtonPressed()
    {
      // Byte code:
      //   0: iconst_1
      //   1: anewarray 19	java/lang/Object
      //   4: astore_1
      //   5: aload_1
      //   6: iconst_0
      //   7: aload_0
      //   8: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$8:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   11: invokestatic 23	com/quizup/core/activities/ActivityNotificationHelper:access$500	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Ljava/lang/String;
      //   14: aastore
      //   15: ldc 25
      //   17: aload_1
      //   18: invokestatic 31	o/ךּ:ˊ	(Ljava/lang/String;[Ljava/lang/Object;)V
      //   21: goto +11 -> 32
      //   24: astore 11
      //   26: aload 11
      //   28: invokevirtual 37	java/lang/Throwable:getCause	()Ljava/lang/Throwable;
      //   31: athrow
      //   32: ldc 39
      //   34: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   37: ldc 46
      //   39: aconst_null
      //   40: invokevirtual 52	java/lang/Class:getMethod	(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;
      //   43: aconst_null
      //   44: aconst_null
      //   45: invokevirtual 58	java/lang/reflect/Method:invoke	(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
      //   48: astore_2
      //   49: aload_0
      //   50: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$8:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   53: invokestatic 61	com/quizup/core/activities/ActivityNotificationHelper:access$300	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Ljava/lang/String;
      //   56: astore_3
      //   57: ldc 39
      //   59: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   62: ldc 63
      //   64: invokevirtual 67	java/lang/Class:getField	(Ljava/lang/String;)Ljava/lang/reflect/Field;
      //   67: aload_2
      //   68: aload_3
      //   69: invokevirtual 73	java/lang/reflect/Field:set	(Ljava/lang/Object;Ljava/lang/Object;)V
      //   72: aload_0
      //   73: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$8:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   76: invokestatic 76	com/quizup/core/activities/ActivityNotificationHelper:access$600	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Ljava/lang/String;
      //   79: astore 4
      //   81: goto +11 -> 92
      //   84: astore 10
      //   86: aload 10
      //   88: invokevirtual 37	java/lang/Throwable:getCause	()Ljava/lang/Throwable;
      //   91: athrow
      //   92: iconst_1
      //   93: anewarray 19	java/lang/Object
      //   96: dup
      //   97: iconst_0
      //   98: aload 4
      //   100: aastore
      //   101: astore 5
      //   103: ldc 78
      //   105: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   108: ldc 46
      //   110: iconst_1
      //   111: anewarray 48	java/lang/Class
      //   114: dup
      //   115: iconst_0
      //   116: ldc 80
      //   118: aastore
      //   119: invokevirtual 52	java/lang/Class:getMethod	(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;
      //   122: aconst_null
      //   123: aload 5
      //   125: invokevirtual 58	java/lang/reflect/Method:invoke	(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
      //   128: pop
      //   129: new 82	android/content/Intent
      //   132: dup
      //   133: aload_0
      //   134: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$8:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   137: invokestatic 86	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
      //   140: ldc 88
      //   142: invokespecial 91	android/content/Intent:<init>	(Landroid/content/Context;Ljava/lang/Class;)V
      //   145: astore 7
      //   147: aload 7
      //   149: ldc 93
      //   151: iconst_1
      //   152: invokevirtual 97	android/content/Intent:putExtra	(Ljava/lang/String;Z)Landroid/content/Intent;
      //   155: pop
      //   156: invokestatic 102	o/ᓑ:'	()V
      //   159: aload_0
      //   160: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$8:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   163: invokestatic 86	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
      //   166: aload 7
      //   168: invokevirtual 108	android/app/Activity:startActivity	(Landroid/content/Intent;)V
      //   171: aload_0
      //   172: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$8:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   175: invokestatic 86	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
      //   178: instanceof 110
      //   181: ifeq +13 -> 194
      //   184: aload_0
      //   185: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$8:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   188: invokestatic 86	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
      //   191: invokevirtual 113	android/app/Activity:finish	()V
      //   194: ldc 115
      //   196: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   199: ldc 116
      //   201: invokevirtual 67	java/lang/Class:getField	(Ljava/lang/String;)Ljava/lang/reflect/Field;
      //   204: aconst_null
      //   205: invokevirtual 120	java/lang/reflect/Field:get	(Ljava/lang/Object;)Ljava/lang/Object;
      //   208: astore 9
      //   210: ldc 115
      //   212: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   215: ldc 122
      //   217: invokevirtual 67	java/lang/Class:getField	(Ljava/lang/String;)Ljava/lang/reflect/Field;
      //   220: aconst_null
      //   221: aload 9
      //   223: invokevirtual 73	java/lang/reflect/Field:set	(Ljava/lang/Object;Ljava/lang/Object;)V
      //   226: return
      //
      // Exception table:
      //   from	to	target	type
      //   32	49	24	finally
      //   92	129	84	finally
    }

    public void rightButtonPressed()
    {
      Object[] arrayOfObject1 = new Object[1];
      arrayOfObject1[0] = ActivityNotificationHelper.this.notificationId;
      ךּ.ˊ("NOTIFICATION_DELETE", arrayOfObject1);
      ᓑ.ʻ();
      Object[] arrayOfObject2 = new Object[1];
      arrayOfObject2[0] = ActivityNotificationHelper.this.notificationGameId;
      ךּ.ˊ("REJECT_GAME_CHALLNGE", arrayOfObject2);
    }
  };
  protected DialogEventListener challengeRequestListener = new DialogEventListener()
  {
    public void dialogClosed()
    {
    }

    // ERROR //
    public void leftButtonPressed()
    {
      // Byte code:
      //   0: iconst_1
      //   1: anewarray 19	java/lang/Object
      //   4: astore_1
      //   5: aload_1
      //   6: iconst_0
      //   7: aload_0
      //   8: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$7:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   11: invokestatic 23	com/quizup/core/activities/ActivityNotificationHelper:access$500	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Ljava/lang/String;
      //   14: aastore
      //   15: ldc 25
      //   17: aload_1
      //   18: invokestatic 31	o/ךּ:ˊ	(Ljava/lang/String;[Ljava/lang/Object;)V
      //   21: goto +11 -> 32
      //   24: astore 11
      //   26: aload 11
      //   28: invokevirtual 37	java/lang/Throwable:getCause	()Ljava/lang/Throwable;
      //   31: athrow
      //   32: ldc 39
      //   34: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   37: ldc 46
      //   39: aconst_null
      //   40: invokevirtual 52	java/lang/Class:getMethod	(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;
      //   43: aconst_null
      //   44: aconst_null
      //   45: invokevirtual 58	java/lang/reflect/Method:invoke	(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
      //   48: astore_2
      //   49: aload_0
      //   50: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$7:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   53: invokestatic 61	com/quizup/core/activities/ActivityNotificationHelper:access$300	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Ljava/lang/String;
      //   56: astore_3
      //   57: ldc 39
      //   59: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   62: ldc 63
      //   64: invokevirtual 67	java/lang/Class:getField	(Ljava/lang/String;)Ljava/lang/reflect/Field;
      //   67: aload_2
      //   68: aload_3
      //   69: invokevirtual 73	java/lang/reflect/Field:set	(Ljava/lang/Object;Ljava/lang/Object;)V
      //   72: aload_0
      //   73: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$7:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   76: invokestatic 76	com/quizup/core/activities/ActivityNotificationHelper:access$600	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Ljava/lang/String;
      //   79: astore 4
      //   81: goto +11 -> 92
      //   84: astore 10
      //   86: aload 10
      //   88: invokevirtual 37	java/lang/Throwable:getCause	()Ljava/lang/Throwable;
      //   91: athrow
      //   92: iconst_1
      //   93: anewarray 19	java/lang/Object
      //   96: dup
      //   97: iconst_0
      //   98: aload 4
      //   100: aastore
      //   101: astore 5
      //   103: ldc 78
      //   105: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   108: ldc 46
      //   110: iconst_1
      //   111: anewarray 48	java/lang/Class
      //   114: dup
      //   115: iconst_0
      //   116: ldc 80
      //   118: aastore
      //   119: invokevirtual 52	java/lang/Class:getMethod	(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;
      //   122: aconst_null
      //   123: aload 5
      //   125: invokevirtual 58	java/lang/reflect/Method:invoke	(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;
      //   128: pop
      //   129: new 82	android/content/Intent
      //   132: dup
      //   133: aload_0
      //   134: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$7:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   137: invokestatic 86	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
      //   140: ldc 88
      //   142: invokespecial 91	android/content/Intent:<init>	(Landroid/content/Context;Ljava/lang/Class;)V
      //   145: astore 7
      //   147: aload 7
      //   149: ldc 93
      //   151: iconst_1
      //   152: invokevirtual 97	android/content/Intent:putExtra	(Ljava/lang/String;Z)Landroid/content/Intent;
      //   155: pop
      //   156: invokestatic 102	o/ᓑ:'	()V
      //   159: aload_0
      //   160: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$7:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   163: invokestatic 86	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
      //   166: aload 7
      //   168: invokevirtual 108	android/app/Activity:startActivity	(Landroid/content/Intent;)V
      //   171: aload_0
      //   172: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$7:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   175: invokestatic 86	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
      //   178: instanceof 110
      //   181: ifeq +13 -> 194
      //   184: aload_0
      //   185: getfield 12	com/quizup/core/activities/ActivityNotificationHelper$7:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
      //   188: invokestatic 86	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
      //   191: invokevirtual 113	android/app/Activity:finish	()V
      //   194: ldc 115
      //   196: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   199: ldc 117
      //   201: invokevirtual 67	java/lang/Class:getField	(Ljava/lang/String;)Ljava/lang/reflect/Field;
      //   204: aconst_null
      //   205: invokevirtual 121	java/lang/reflect/Field:get	(Ljava/lang/Object;)Ljava/lang/Object;
      //   208: astore 9
      //   210: ldc 115
      //   212: invokestatic 45	o/Ꮀ$Ɩ:ィ	(Ljava/lang/String;)Ljava/lang/Class;
      //   215: ldc 123
      //   217: invokevirtual 67	java/lang/Class:getField	(Ljava/lang/String;)Ljava/lang/reflect/Field;
      //   220: aconst_null
      //   221: aload 9
      //   223: invokevirtual 73	java/lang/reflect/Field:set	(Ljava/lang/Object;Ljava/lang/Object;)V
      //   226: return
      //
      // Exception table:
      //   from	to	target	type
      //   32	49	24	finally
      //   92	129	84	finally
    }

    public void rightButtonPressed()
    {
      Object[] arrayOfObject1 = new Object[1];
      arrayOfObject1[0] = ActivityNotificationHelper.this.notificationId;
      ךּ.ˊ("NOTIFICATION_DELETE", arrayOfObject1);
      ᓑ.ʻ();
      Object[] arrayOfObject2 = new Object[1];
      arrayOfObject2[0] = ActivityNotificationHelper.this.notificationGameId;
      ךּ.ˊ("REJECT_GAME_CHALLNGE", arrayOfObject2);
    }
  };
  private View.OnClickListener chatClickListener = new View.OnClickListener()
  {
    public void onClick(View paramAnonymousView)
    {
      ActivityNotificationHelper.this.activity.startActivity(new Intent(ActivityNotificationHelper.this.activity, MessagesActivity.class));
    }
  };
  private View.OnClickListener chatDismissListener = new View.OnClickListener()
  {
    public void onClick(View paramAnonymousView)
    {
      if ((ActivityNotificationHelper.this.mDestroytask != null) && (AsyncTask.Status.FINISHED != ActivityNotificationHelper.this.mDestroytask.getStatus()))
        ActivityNotificationHelper.this.mDestroytask.cancel(true);
      ActivityNotificationHelper.this.activity.getWindowManager().removeView(ActivityNotificationHelper.this.mChatView);
    }
  };
  protected DialogEventListener friendRequestAcceptedListener = new DialogEventListener()
  {
    public void leftButtonPressed()
    {
      ActivityNotificationHelper.this.runMatchUpScene();
    }

    public void rightButtonPressed()
    {
      Intent localIntent = new Intent(ActivityNotificationHelper.this.activity, ProfileActivity.class);
      localIntent.putExtra("player_id", ActivityNotificationHelper.this.notificationPlayer.ˊ);
      ActivityNotificationHelper.this.activity.startActivity(localIntent);
    }
  };
  protected DialogEventListener friendRequestListener = new DialogEventListener()
  {
    public void leftButtonPressed()
    {
      Intent localIntent = new Intent(ActivityNotificationHelper.this.activity, ProfileActivity.class);
      localIntent.putExtra("player_id", ActivityNotificationHelper.this.notificationPlayer.ˊ);
      ActivityNotificationHelper.this.activity.startActivity(localIntent);
      ᒫ localᒫ = new ᒫ(QuizApplication.ˊ.ˋ.ˊ, ActivityNotificationHelper.this.notificationRequestId);
      Boolean[] arrayOfBoolean = new Boolean[1];
      arrayOfBoolean[0] = Boolean.valueOf(false);
      localᒫ.execute(arrayOfBoolean);
    }

    public void rightButtonPressed()
    {
      ᒫ localᒫ = new ᒫ(QuizApplication.ˊ.ˋ.ˊ, ActivityNotificationHelper.this.notificationRequestId);
      Boolean[] arrayOfBoolean = new Boolean[1];
      arrayOfBoolean[0] = Boolean.valueOf(true);
      localᒫ.execute(arrayOfBoolean);
    }
  };
  private View mChatView;
  private AsyncTask<Void, Void, Void> mDestroytask;
  private String notificationGameId;
  private String notificationId;
  private ⅹ notificationPlayer;
  private String notificationRequestId;
  private String notificationSlug;
  protected ᴧ receiver = new ᴧ()
  {
    public void playerFollowed(boolean paramAnonymousBoolean)
    {
      if (ActivityNotificationHelper.this.notificationPlayer != null)
      {
        Ί localΊ = new Ί(ActivityNotificationHelper.this.notificationPlayer);
        QuizApplication.ˊ.ˋ.ᵢ.put(localΊ.ˊ, localΊ);
        ﻟ.ˊ.remove(ActivityNotificationHelper.this.notificationPlayer.ˊ);
        ךּ.ˊ("FOLLOWER_LIST_CHANGED", new Object[0]);
      }
    }

    public void playerUnFollowed(boolean paramAnonymousBoolean)
    {
      if (ActivityNotificationHelper.this.notificationPlayer != null)
      {
        ⅹ localⅹ = QuizApplication.ˊ.ˋ;
        String str = ActivityNotificationHelper.this.notificationPlayer.ˊ;
        localⅹ.ᵢ.remove(str);
        ךּ.ˊ("FOLLOWER_LIST_CHANGED", new Object[0]);
      }
    }
  };

  public ActivityNotificationHelper(Activity paramActivity)
  {
    this.activity = paramActivity;
  }

  private void animateChatView(View paramView)
  {
    ObjectAnimator localObjectAnimator = ObjectAnimator.ofFloat(paramView.findViewById(2131296587), View.TRANSLATION_Y, new float[] { -300.0F, 0.0F });
    localObjectAnimator.setDuration(500L);
    localObjectAnimator.start();
  }

  private Bitmap getTopicBitmap(ȉ paramȉ)
  {
    QuizApplication localQuizApplication = QuizApplication.ˊ;
    String str = paramȉ.ـ;
    Drawable localDrawable = localQuizApplication.ʻ.ˊ(str, -1);
    Bitmap localBitmap = Bitmap.createBitmap(localDrawable.getIntrinsicWidth(), localDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas localCanvas = new Canvas(localBitmap);
    localDrawable.setBounds(0, 0, localCanvas.getWidth(), localCanvas.getHeight());
    localDrawable.draw(localCanvas);
    return localBitmap;
  }

  private View setChatView(ⅹ paramⅹ, String paramString)
  {
    this.mChatView = this.activity.getLayoutInflater().inflate(2130903084, null);
    String str1;
    if (paramⅹ.ͺ.startsWith("file://"))
      str1 = paramⅹ.ͺ.replaceFirst("file://", "");
    else
      str1 = paramⅹ.ͺ;
    String str2 = paramⅹ.ˊ;
    Activity localActivity = this.activity;
    boolean bool = paramⅹ.ͺ.startsWith("file://");
    String str3 = str1;
    Bitmap localBitmap;
    if (bool)
    {
      int i = ﭠ.ˊ(localActivity, str3);
      Resources localResources = localActivity.getResources();
      BitmapFactory.Options localOptions = new BitmapFactory.Options();
      localOptions.inPurgeable = true;
      localOptions.inInputShareable = true;
      localOptions.inSampleSize = 2;
      localBitmap = BitmapFactory.decodeResource(localResources, i, localOptions);
    }
    else
    {
      localBitmap = Ί.1.ˋ(localActivity, str2, str3);
    }
    ((ProfilePicture)this.mChatView.findViewById(2131296463)).setPicture(localBitmap);
    ((TextView)this.mChatView.findViewById(2131296466)).setText(paramⅹ.ˎ);
    ((TextView)this.mChatView.findViewById(2131296589)).setText(paramString);
    this.mChatView.setOnClickListener(this.chatClickListener);
    this.mChatView.findViewById(2131296588).setOnClickListener(this.chatDismissListener);
    return this.mChatView;
  }

  public void onChallengeCompleteNotification(ⅹ paramⅹ, String paramString, ȉ paramȉ)
  {
    String str1;
    if (paramⅹ.ͺ.startsWith("file://"))
      str1 = paramⅹ.ͺ.replaceFirst("file://", "");
    else
      str1 = paramⅹ.ͺ;
    String str2 = paramⅹ.ˊ;
    Activity localActivity1 = this.activity;
    boolean bool = paramⅹ.ͺ.startsWith("file://");
    String str3 = str1;
    Bitmap localBitmap1;
    if (bool)
    {
      int i = ﭠ.ˊ(localActivity1, str3);
      Resources localResources = localActivity1.getResources();
      BitmapFactory.Options localOptions = new BitmapFactory.Options();
      localOptions.inPurgeable = true;
      localOptions.inInputShareable = true;
      localOptions.inSampleSize = 2;
      localBitmap1 = BitmapFactory.decodeResource(localResources, i, localOptions);
    }
    else
    {
      localBitmap1 = Ί.1.ˋ(localActivity1, str2, str3);
    }
    Bitmap localBitmap2 = getTopicBitmap(paramȉ);
    this.notificationGameId = paramString;
    this.notificationPlayer = paramⅹ;
    ﻟ.ᐝ(paramString);
    Activity localActivity2 = this.activity;
    DialogEventListener localDialogEventListener = this.challengeCompleteListener;
    String str4 = paramⅹ.ˎ;
    String str5 = paramȉ.ˑ;
    new ṛ(localActivity2, localDialogEventListener, localBitmap1, str4, str5, localBitmap2).ˎ();
  }

  public void onChallengeNudgeNotification(ⅹ paramⅹ, String paramString1, ȉ paramȉ, String paramString2)
  {
    String str1;
    if (paramⅹ.ͺ.startsWith("file://"))
      str1 = paramⅹ.ͺ.replaceFirst("file://", "");
    else
      str1 = paramⅹ.ͺ;
    String str2 = paramⅹ.ˊ;
    Activity localActivity = this.activity;
    boolean bool = paramⅹ.ͺ.startsWith("file://");
    String str3 = str1;
    Bitmap localBitmap1;
    if (bool)
    {
      int i = ﭠ.ˊ(localActivity, str3);
      Resources localResources = localActivity.getResources();
      BitmapFactory.Options localOptions = new BitmapFactory.Options();
      localOptions.inPurgeable = true;
      localOptions.inInputShareable = true;
      localOptions.inSampleSize = 2;
      localBitmap1 = BitmapFactory.decodeResource(localResources, i, localOptions);
    }
    else
    {
      localBitmap1 = Ί.1.ˋ(localActivity, str2, str3);
    }
    Bitmap localBitmap2 = getTopicBitmap(paramȉ);
    String str4 = paramⅹ.ˎ;
    this.notificationId = paramString2;
    String str5 = paramȉ.ˑ;
    this.notificationGameId = paramString1;
    this.notificationSlug = paramȉ.ـ;
    ﻟ.ᐝ(paramString1);
    new ‿(this.activity, this.challengeNudgeListener, localBitmap1, str4, str5, localBitmap2, 2131493228).ˎ();
  }

  public void onChallengeRequestNotification(ⅹ paramⅹ, String paramString1, ȉ paramȉ, String paramString2)
  {
    String str1;
    if (paramⅹ.ͺ.startsWith("file://"))
      str1 = paramⅹ.ͺ.replaceFirst("file://", "");
    else
      str1 = paramⅹ.ͺ;
    String str2 = paramⅹ.ˊ;
    Activity localActivity = this.activity;
    boolean bool = paramⅹ.ͺ.startsWith("file://");
    String str3 = str1;
    Bitmap localBitmap1;
    if (bool)
    {
      int i = ﭠ.ˊ(localActivity, str3);
      Resources localResources = localActivity.getResources();
      BitmapFactory.Options localOptions = new BitmapFactory.Options();
      localOptions.inPurgeable = true;
      localOptions.inInputShareable = true;
      localOptions.inSampleSize = 2;
      localBitmap1 = BitmapFactory.decodeResource(localResources, i, localOptions);
    }
    else
    {
      localBitmap1 = Ί.1.ˋ(localActivity, str2, str3);
    }
    Bitmap localBitmap2 = getTopicBitmap(paramȉ);
    String str4 = paramⅹ.ˎ;
    this.notificationId = paramString2;
    String str5 = paramȉ.ˑ;
    this.notificationGameId = paramString1;
    this.notificationSlug = paramȉ.ـ;
    ﻟ.ᐝ(paramString1);
    new ‿(this.activity, this.challengeRequestListener, localBitmap1, str4, str5, localBitmap2, 2131493227).ˎ();
  }

  public void onChatRecieved(ⅹ paramⅹ, String paramString)
  {
    View localView = setChatView(paramⅹ, paramString);
    WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams(-1, -2, 2, 8, -3);
    localLayoutParams.gravity = 51;
    localLayoutParams.x = 0;
    localLayoutParams.y = 0;
    this.activity.getWindowManager().addView(localView, localLayoutParams);
    animateChatView(localView);
    this.mDestroytask = new AsyncTask()
    {
      protected Void doInBackground(Void[] paramAnonymousArrayOfVoid)
      {
        try
        {
          Thread.sleep(10000L);
        }
        catch (InterruptedException localInterruptedException)
        {
          localInterruptedException.printStackTrace();
        }
        return null;
      }

      // ERROR //
      protected void onPostExecute(Void paramAnonymousVoid)
      {
        // Byte code:
        //   0: aload_0
        //   1: getfield 16	com/quizup/core/activities/ActivityNotificationHelper$1:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
        //   4: invokestatic 52	com/quizup/core/activities/ActivityNotificationHelper:access$000	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/view/View;
        //   7: ifnull +39 -> 46
        //   10: aload_0
        //   11: getfield 16	com/quizup/core/activities/ActivityNotificationHelper$1:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
        //   14: invokestatic 56	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
        //   17: invokevirtual 62	android/app/Activity:getWindowManager	()Landroid/view/WindowManager;
        //   20: ifnull +26 -> 46
        //   23: aload_0
        //   24: getfield 16	com/quizup/core/activities/ActivityNotificationHelper$1:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
        //   27: invokestatic 56	com/quizup/core/activities/ActivityNotificationHelper:access$100	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/app/Activity;
        //   30: invokevirtual 62	android/app/Activity:getWindowManager	()Landroid/view/WindowManager;
        //   33: aload_0
        //   34: getfield 16	com/quizup/core/activities/ActivityNotificationHelper$1:this$0	Lcom/quizup/core/activities/ActivityNotificationHelper;
        //   37: invokestatic 52	com/quizup/core/activities/ActivityNotificationHelper:access$000	(Lcom/quizup/core/activities/ActivityNotificationHelper;)Landroid/view/View;
        //   40: invokeinterface 68 2 0
        //   45: return
        //   46: return
        //
        // Exception table:
        //   from	to	target	type
        //   23	45	46	java/lang/Exception
      }
    };
    this.mDestroytask.execute(new Void[0]);
  }

  public void onFollowerAddedNotification(ⅹ paramⅹ)
  {
    String str1;
    if (paramⅹ.ͺ.startsWith("file://"))
      str1 = paramⅹ.ͺ.replaceFirst("file://", "");
    else
      str1 = paramⅹ.ͺ;
    String str2 = paramⅹ.ˊ;
    Activity localActivity = this.activity;
    boolean bool = paramⅹ.ͺ.startsWith("file://");
    String str3 = str1;
    Bitmap localBitmap;
    if (bool)
    {
      int i = ﭠ.ˊ(localActivity, str3);
      Resources localResources = localActivity.getResources();
      BitmapFactory.Options localOptions = new BitmapFactory.Options();
      localOptions.inPurgeable = true;
      localOptions.inInputShareable = true;
      localOptions.inSampleSize = 2;
      localBitmap = BitmapFactory.decodeResource(localResources, i, localOptions);
    }
    else
    {
      localBitmap = Ί.1.ˋ(localActivity, str2, str3);
    }
    this.notificationPlayer = paramⅹ;
    ﻟ.ˏ(paramⅹ.ˊ);
    ﻟ.ˊ(paramⅹ);
    new ṛ(this.activity, this.addFriendListener, localBitmap, paramⅹ.ˎ).ˎ();
  }

  public void onFriendRequestAcceptedNotification(ⅹ paramⅹ)
  {
    String str1;
    if (paramⅹ.ͺ.startsWith("file://"))
      str1 = paramⅹ.ͺ.replaceFirst("file://", "");
    else
      str1 = paramⅹ.ͺ;
    String str2 = paramⅹ.ˊ;
    Activity localActivity = this.activity;
    Bitmap localBitmap;
    if (paramⅹ.ͺ.startsWith("file://"))
    {
      int i = ﭠ.ˊ(localActivity, str1);
      Resources localResources = localActivity.getResources();
      BitmapFactory.Options localOptions = new BitmapFactory.Options();
      localOptions.inPurgeable = true;
      localOptions.inInputShareable = true;
      localOptions.inSampleSize = 2;
      localBitmap = BitmapFactory.decodeResource(localResources, i, localOptions);
    }
    else
    {
      localBitmap = Ί.1.ˋ(localActivity, str2, str1);
    }
    this.notificationPlayer = paramⅹ;
    ﻟ.ˏ(paramⅹ.ˊ);
    ⅹ localⅹ = QuizApplication.ᐝ().ˋ;
    Ί localΊ = new Ί(this.notificationPlayer);
    localⅹ.ᵢ.put(localΊ.ˊ, localΊ);
    new ṛ(this.activity, this.friendRequestAcceptedListener, localBitmap, paramⅹ.ˎ).ˎ();
  }

  public void onFriendRequestedNotification(ⅹ paramⅹ, String paramString)
  {
    String str1;
    if (paramⅹ.ͺ.startsWith("file://"))
      str1 = paramⅹ.ͺ.replaceFirst("file://", "");
    else
      str1 = paramⅹ.ͺ;
    String str2 = paramⅹ.ˊ;
    Activity localActivity = this.activity;
    boolean bool = paramⅹ.ͺ.startsWith("file://");
    String str3 = str1;
    Bitmap localBitmap;
    if (bool)
    {
      int i = ﭠ.ˊ(localActivity, str3);
      Resources localResources = localActivity.getResources();
      BitmapFactory.Options localOptions = new BitmapFactory.Options();
      localOptions.inPurgeable = true;
      localOptions.inInputShareable = true;
      localOptions.inSampleSize = 2;
      localBitmap = BitmapFactory.decodeResource(localResources, i, localOptions);
    }
    else
    {
      localBitmap = Ί.1.ˋ(localActivity, str2, str3);
    }
    this.notificationPlayer = paramⅹ;
    this.notificationRequestId = paramString;
    ﻟ.ˏ(paramⅹ.ˊ);
    ﻟ.ˊ(paramⅹ);
    new ὶ(this.activity, this.friendRequestListener, localBitmap, paramⅹ.ˎ).ˎ();
  }

  protected void runMatchUpScene()
  {
    ﺩ.ˊ("opponent", this.notificationPlayer.ˊ);
    Intent localIntent = new Intent(this.activity, VsActivity.class);
    localIntent.putExtra("is_challenge", true);
    this.activity.startActivity(localIntent);
  }

  public static class DialogEventListener
    implements ‿.if
  {
    public void dialogClosed()
    {
    }

    public void leftButtonPressed()
    {
    }

    public void rightButtonPressed()
    {
    }
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.quizup.core.activities.ActivityNotificationHelper
 * JD-Core Version:    0.6.2
 */


text:
const sinon = require("sinon");
const should = require("should");

const Room = require("../../src/core/Room");
const { KuzzleEventEmitter } = require("../../src/core/KuzzleEventEmitter");

describe("Room", () => {
  const eventEmitter = new KuzzleEventEmitter();
  const options = { opt: "in" };

  let controller;

  beforeEach(() => {
    controller = {
      kuzzle: {
        query: sinon.stub().resolves(),
        addListener: (evt, listener) => {
          eventEmitter.addListener(evt, listener);
        },
        removeListener: (evt, listener) => {
          eventEmitter.removeListener(evt, listener);
        },
        tokenExpired: sinon.stub(),
        protocol: new KuzzleEventEmitter(),
        emit: sinon.stub(),
      },
      tokenExpired: sinon.stub(),
    };

    controller.kuzzle.protocol.id = "kuz-protocol-id";
  });

  describe("constructor", () => {
    it("should create a Room instance with good properties", () => {
      const body = { foo: "bar" };
      const cb = sinon.stub();

      controller.kuzzle.autoResubscribe = "default";

      const room = new Room(
        controller,
        "index",
        "collection",
        body,
        cb,
        options
      );

      should(room.controller).be.equal(controller);
      should(room.kuzzle).be.equal(controller.kuzzle);
      should(room.index).be.equal("index");
      should(room.collection).be.equal("collection");

      should(room.callback).be.equal(cb);
      should(room.options).be.equal(options);

      should(room.id).be.null();
      should(room.channel).be.null();

      should(room.request.controller).be.equal("realtime");
      should(room.request.action).be.equal("subscribe");
      should(room.request.index).be.equal("index");
      should(room.request.collection).be.equal("collection");
      should(room.request.body).be.equal(body);
      should(room.request.scope).be.undefined();
      should(room.request.state).be.undefined();
      should(room.request.users).be.undefined();
      should(room.request.volatile).be.undefined();

      should(room.autoResubscribe).be.equal("default");
      should(room.subscribeToSelf).be.a.Boolean().and.be.True();
    });

    it("should handle scope/state/users/volatile options", () => {
      const opts = {
        scope: "scope",
        state: "state",
        users: "users",
        volatile: "volatile",
      };
      const body = { foo: "bar" };
      const cb = sinon.stub();

      const room = new Room(controller, "index", "collection", body, cb, opts);

      should(room.request.scope).be.equal("scope");
      should(room.request.state).be.equal("state");
      should(room.request.users).be.equal("users");
      should(room.request.volatile).be.equal("volatile");
    });

    it("should handle autoResubscribe option", () => {
      const body = { foo: "bar" };
      const cb = sinon.stub();

      controller.kuzzle.autoResubscribe = "default";

      const room1 = new Room(controller, "index", "collection", body, cb, {
        autoResubscribe: true,
      });
      const room2 = new Room(controller, "index", "collection", body, cb, {
        autoResubscribe: false,
      });
      const room3 = new Room(controller, "index", "collection", body, cb, {
        autoResubscribe: "foobar",
      });

      should(room1.autoResubscribe).be.a.Boolean().and.be.True();
      should(room2.autoResubscribe).be.a.Boolean().and.be.False();
      should(room3.autoResubscribe).be.equal("default");
    });

    it("should handle subscribeToSelf option", () => {
      const body = { foo: "bar" };
      const cb = sinon.stub();

      const room1 = new Room(controller, "index", "collection", body, cb, {
        subscribeToSelf: true,
      });
      const room2 = new Room(controller, "index", "collection", body, cb, {
        subscribeToSelf: false,
      });
      const room3 = new Room(controller, "index", "collection", body, cb, {
        subscribeToSelf: "foobar",
      });

      should(room1.subscribeToSelf).be.a.Boolean().and.be.True();
      should(room2.subscribeToSelf).be.a.Boolean().and.be.False();
      should(room3.subscribeToSelf).be.a.Boolean().and.be.True();
    });
  });

  describe("subscribe", () => {
    const response = {
      result: {
        roomId: "my-room-id",
        channel: "subscription-channel",
      },
    };

    beforeEach(() => {
      controller.kuzzle.query.resolves(response);
    });

    it("should call realtime/subscribe action with subscribe filters and return a promise that resolve the roomId and channel", () => {
      const opts = {
        opt: "in",
        scope: "in",
        state: "done",
        users: "all",
        volatile: { bar: "foo" },
      };
      const body = { foo: "bar" };
      const cb = sinon.stub();
      const room = new Room(controller, "index", "collection", body, cb, opts);

      return room.subscribe().then((res) => {
        should(controller.kuzzle.query)
          .be.calledOnce()
          .be.calledWith(
            {
              controller: "realtime",
              action: "subscribe",
              index: "index",
              collection: "collection",
              body: { foo: "bar" },
              scope: "in",
              state: "done",
              users: "all",
              volatile: { bar: "foo" },
            },
            opts
          );

        should(res).be.equal(response);
      });
    });

    it('should set "id" and "channel" properties', () => {
      const opts = {
        opt: "in",
        scope: "in",
        state: "done",
        users: "all",
        volatile: { bar: "foo" },
      };
      const body = { foo: "bar" };
      const cb = sinon.stub();
      const room = new Room(controller, "index", "collection", body, cb, opts);

      return room.subscribe().then(() => {
        should(room.id).be.equal("my-room-id");
        should(room.channel).be.equal("subscription-channel");
      });
    });

    it("should call _channelListener while receiving data on the current channel", () => {
      const opts = {
        opt: "in",
        scope: "in",
        state: "done",
        users: "all",
        volatile: { bar: "foo" },
      };
      const body = { foo: "bar" };
      const cb = sinon.stub();
      const room = new Room(controller, "index", "collection", body, cb, opts);

      room._channelListener = sinon.stub();

      return room.subscribe().then(() => {
        controller.kuzzle.protocol.emit("my-room-id", "message 1");
        controller.kuzzle.protocol.emit("subscription-channel", "message 2");
        controller.kuzzle.protocol.emit("subscription-channel", "message 3");
        should(room._channelListener).be.calledTwice();
        should(room._channelListener.firstCall).be.calledWith("message 2");
        should(room._channelListener.secondCall).be.calledWith("message 3");
      });
    });
  });

  describe("removeListeners", () => {
    let room;

    beforeEach(() => {
      room = new Room(
        controller,
        "index",
        "collection",
        { foo: "bar" },
        sinon.stub(),
        options
      );
      room.id = "my-room-id";
      room.channel = "subscription-channel";
    });

    it("should not listen to channel messages anymore", () => {
      room._channelListener = sinon.stub();
      controller.kuzzle.protocol.on(
        "subscription-channel",
        room._channelListener
      );

      should(room._channelListener).not.be.called();
      controller.kuzzle.protocol.emit("subscription-channel", "message");
      should(room._channelListener).be.calledOnce();

      room._channelListener.reset();
      room.removeListeners();
      controller.kuzzle.protocol.emit("subscription-channel", "message");
      should(room._channelListener).not.be.called();
    });
  });

  describe("_channelListener", () => {
    let cb;
    let room;

    beforeEach(() => {
      cb = sinon.stub();
      room = new Room(
        controller,
        "index",
        "collection",
        { foo: "bar" },
        cb,
        options
      );
      room.id = "my-room-id";
      room.channel = "subscription-channel";
    });

    it("should call the callback if subscribeToSelf option is TRUE and the notification message comes from another user", () => {
      room.subscribeToSelf = true;

      const data = { foo: "bar" };

      room._channelListener(data);
      should(cb).be.calledOnce().be.calledWith(data);

      cb.reset();
      data.volatile = { sdkInstanceId: "another-client" };
      room._channelListener(data);
      should(cb).be.calledOnce().be.calledWith(data);
    });

    it("should call the callback if subscribeToSelf option is FALSE and the notification message comes from another user", () => {
      room.subscribeToSelf = false;

      const data = { foo: "bar" };

      room._channelListener(data);
      should(cb).be.calledOnce().be.calledWith(data);

      cb.reset();
      data.volatile = { sdkInstanceId: "another-client" };
      room._channelListener(data);
      should(cb).be.calledOnce().be.calledWith(data);
    });

    it("should call the callback if subscribeToSelf option is TRUE and the notification message comes from current user", () => {
      room.subscribeToSelf = true;

      const data = {
        foo: "bar",
        volatile: { sdkInstanceId: "kuz-protocol-id" },
      };

      room._channelListener(data);
      should(cb).be.calledOnce().be.calledWith(data);
    });

    it("should call the callback if subscribeToSelf option is FALSE and the notification message comes from current user", () => {
      room.subscribeToSelf = false;

      const data = {
        foo: "bar",
        volatile: { sdkInstanceId: "kuz-protocol-id" },
      };

      room._channelListener(data);
      should(cb).not.be.called();
    });

    it("should redirect a tokenExpired notification to kuzzle", () => {
      const data = {
        type: "TokenExpired",
        foo: "bar",
      };

      room._channelListener(data);

      should(cb).not.be.called();
      should(controller.kuzzle.tokenExpired).be.called();
    });

    it("should emit an event on callback promise rejection", async () => {
      const data = { foo: "bar" };
      const callbackError = new Error("callbackPromiseRejection");

      cb.rejects(callbackError);

      await room._channelListener(data);

      should(cb).be.calledOnce().be.calledWith(data);

      should(controller.kuzzle.emit)
        .be.calledOnce()
        .be.calledWithMatch("callbackError", { error: callbackError });
    });
  });
});


text:
using AllReady.Security;
using AllReady.Security.Middleware;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Authentication.Twitter;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;

namespace AllReady.Configuration
{
    internal static class Authentication
    {
        //Handles remote login failure typically where user doesn't give consent
        private static Task HandleRemoteLoginFailure(FailureContext ctx)
        {
            ctx.Response.Redirect("/Account/Login");
            ctx.HandleResponse();
            return Task.FromResult(0);
        }

        internal static void ConfigureAuthentication(IApplicationBuilder app, IConfiguration configuration)
        {
            // Add cookie-based authentication to the request pipeline.
            app.UseIdentity();

            // Add token-based protection to the request inject pipeline
            app.UseTokenProtection(new TokenProtectedResourceOptions
            {
                Path = "/api/request",
                PolicyName = "api-request-injest"
            });

            // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
            // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
            if (configuration["Authentication:Facebook:AppId"] != null)
            {
                var options = new FacebookOptions
                {
                    AppId = configuration["Authentication:Facebook:AppId"],
                    AppSecret = configuration["Authentication:Facebook:AppSecret"],
                    BackchannelHttpHandler = new FacebookBackChannelHandler(),
                    UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name",
                    Events = new OAuthEvents()
                    {
                        OnRemoteFailure = ctx => HandleRemoteLoginFailure(ctx)
                    }
                };
                options.Scope.Add("email");

                app.UseFacebookAuthentication(options);
            }

            if (configuration["Authentication:MicrosoftAccount:ClientId"] != null)
            {
                var options = new MicrosoftAccountOptions
                {
                    ClientId = configuration["Authentication:MicrosoftAccount:ClientId"],
                    ClientSecret = configuration["Authentication:MicrosoftAccount:ClientSecret"],
                    Events = new OAuthEvents()
                    {
                        OnRemoteFailure = ctx => HandleRemoteLoginFailure(ctx)
                    }
                };

                app.UseMicrosoftAccountAuthentication(options);
            }

            //http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap
            if (configuration["Authentication:Twitter:ConsumerKey"] != null)
            {
                var options = new TwitterOptions
                {
                    ConsumerKey = configuration["Authentication:Twitter:ConsumerKey"],
                    ConsumerSecret = configuration["Authentication:Twitter:ConsumerSecret"]
                    ,
                    Events = new TwitterEvents()
                    {

                        OnRemoteFailure = ctx => HandleRemoteLoginFailure(ctx)
                    }
                };

                app.UseTwitterAuthentication(options);
            }

            if (configuration["Authentication:Google:ClientId"] != null)
            {
                var options = new GoogleOptions
                {
                    ClientId = configuration["Authentication:Google:ClientId"],
                    ClientSecret = configuration["Authentication:Google:ClientSecret"],
                    Events = new OAuthEvents()
                    {
                        OnRemoteFailure = ctx => HandleRemoteLoginFailure(ctx)
                    }
                };

                app.UseGoogleAuthentication(options);
            }
        }

    }
}


text:
import React from 'react';

export default class Align extends React.Component {
    getAlignClass = () => {
        const { node } = this.props;
        switch (node.data.get('align')) {
            case 'text-right':
                return 'text-right';
            case 'text-left':
                return 'text-left';
            case 'text-center':
                return 'text-center';
            case 'pull-right':
                return 'pull-right';
            case 'pull-left':
                return 'pull-left';
        }
    };

    render = () => {
        const { node, attributes, children } = this.props;
        const className = this.getAlignClass();

        return (
            <div {...attributes} className={className}>
                {children}
            </div>
        );
    };
}