<commit_before>import React from 'react';
import { shallow, mount } from 'enzyme';
import { Collapse } from '..';

describe('Collapse', () => {
  let isOpen;
  let wrapper;
  const toggle = () => {
    isOpen = !isOpen;
    if (wrapper != null) {
      wrapper.setProps({ isOpen });
    }
  };

  beforeEach(() => {
    isOpen = false;
    jest.useFakeTimers();
  });

  afterEach(() => {
    // fast forward time for collapse to fade out
    jest.runTimersToTime(400);
    jest.clearAllTimers();
  });

  it('should render children', () => {
    wrapper = mount(
      <Collapse>

hello

      </Collapse>,
    );
    expect(wrapper.find('p').text()).toBe('hello');
  });

  it('should have default isOpen value', () => {
    wrapper = shallow(<Collapse />);
    expect(wrapper.instance().props.isOpen).toEqual(false);
  });

  it('should render with class "collapse"', () => {
    wrapper = mount(<Collapse />);
    expect(wrapper.find('div').hasClass('collapse')).toEqual(true);
  });

  it('should render with class "collapse-horizontal" if it has prop horizontal', () => {
    wrapper = mount(<Collapse horizontal />);
    expect(wrapper.find('div').hasClass('collapse-horizontal')).toEqual(true);
  });

  it('should render with class "navbar-collapse" if it has prop navbar', () => {
    wrapper = mount(<Collapse navbar />);
    expect(wrapper.find('div').hasClass('navbar-collapse')).toEqual(true);
  });

  it('should render with class "show" when isOpen is true', () => {
    wrapper = mount(<Collapse isOpen />);
    expect(wrapper.find('div').hasClass('show')).toEqual(true);
  });

  it('should set height to null when isOpen is true', () => {
    wrapper = shallow(<Collapse isOpen />);
    expect(wrapper.state('dimension')).toBe(null);
  });

  it('should not set height when isOpen is false', () => {
    wrapper = shallow(<Collapse isOpen={false} />);
    expect(wrapper.state('dimension')).toBe(null);
  });

  it('should forward all styles', () => {
    wrapper = mount(<Collapse isOpen style={{ backgroundColor: 'black' }} />);
    expect(wrapper.find('div').prop('style').backgroundColor).toBe('black');
  });

  it('should forward all callbacks', () => {
    const callbacks = {
      onEnter: jest.fn(),
      onEntering: jest.fn(),
      onEntered: jest.fn(),
      onExit: jest.fn(),
      onExiting: jest.fn(),
      onExited: jest.fn(),
    };
    wrapper = mount(<Collapse isOpen={isOpen} {...callbacks} />);
    toggle();
    expect(callbacks.onEnter).toHaveBeenCalled();
    expect(callbacks.onEntering).toHaveBeenCalled();
    expect(callbacks.onEntered).not.toHaveBeenCalled();
    jest.runTimersToTime(350);
    expect(callbacks.onEntered).toHaveBeenCalled();
    expect(callbacks.onExit).not.toHaveBeenCalled();

    toggle();
    expect(callbacks.onExit).toHaveBeenCalled();
    expect(callbacks.onExiting).toHaveBeenCalled();
    expect(callbacks.onExited).not.toHaveBeenCalled();
    jest.runTimersToTime(350);
    expect(callbacks.onExiting).toHaveBeenCalled();
    expect(callbacks.onExited).toHaveBeenCalled();

    wrapper.unmount();
  });

  it('should apply correct bootstrap classes', () => {
    wrapper = mount(<Collapse isOpen={isOpen} />);
    toggle();
    expect(wrapper.update().find('div').prop('className')).toBe('collapsing');
    jest.runTimersToTime(350);
    expect(wrapper.update().find('div').prop('className')).toBe(
      'collapse show',
    );

    toggle();
    expect(wrapper.update().find('div').prop('className')).toBe('collapsing');
    jest.runTimersToTime(350);
    expect(wrapper.update().find('div').prop('className')).toBe('collapse');

    wrapper.unmount();
  });

  it('should set inline style to 0 when isOpen change to false', () => {
    isOpen = true;
    wrapper = mount(<Collapse isOpen={isOpen} />);
    toggle();
    expect(wrapper.state('dimension')).toBe(0);
    wrapper.unmount();
  });

  it('should remove inline style when isOpen change to true after transition', () => {
    wrapper = mount(<Collapse isOpen={isOpen} />);
    toggle();
    jest.runTimersToTime(380);
    expect(wrapper.state('dimension')).toBe(null);
    wrapper.unmount();
  });
});
<commit_msg>test: Add a test for strict mode with `Collapse`<commit_after>import React from 'react';
import { shallow, mount } from 'enzyme';
import { Collapse } from '..';

describe('Collapse', () => {
  let isOpen;
  let wrapper;
  const toggle = () => {
    isOpen = !isOpen;
    if (wrapper != null) {
      wrapper.setProps({ isOpen });
    }
  };

  beforeEach(() => {
    isOpen = false;
    jest.useFakeTimers();
  });

  afterEach(() => {
    // fast forward time for collapse to fade out
    jest.runTimersToTime(400);
    jest.clearAllTimers();
  });

  it('should render children', () => {
    wrapper = mount(
      <Collapse>

hello

      </Collapse>,
    );
    expect(wrapper.find('p').text()).toBe('hello');
  });

  it('works with strict mode', () => {
    const spy = jest.spyOn(console, 'error');
    wrapper = mount(<React.StrictMode><Collapse/></React.StrictMode>);
    expect(wrapper.instance()).toBeTruthy();
    expect(spy).not.toHaveBeenCalled();
  })

  it('should have default isOpen value', () => {
    wrapper = shallow(<Collapse />);
    expect(wrapper.instance().props.isOpen).toEqual(false);
  });

  it('should render with class "collapse"', () => {
    wrapper = mount(<Collapse />);
    expect(wrapper.find('div').hasClass('collapse')).toEqual(true);
  });

  it('should render with class "collapse-horizontal" if it has prop horizontal', () => {
    wrapper = mount(<Collapse horizontal />);
    expect(wrapper.find('div').hasClass('collapse-horizontal')).toEqual(true);
  });

  it('should render with class "navbar-collapse" if it has prop navbar', () => {
    wrapper = mount(<Collapse navbar />);
    expect(wrapper.find('div').hasClass('navbar-collapse')).toEqual(true);
  });

  it('should render with class "show" when isOpen is true', () => {
    wrapper = mount(<Collapse isOpen />);
    expect(wrapper.find('div').hasClass('show')).toEqual(true);
  });

  it('should set height to null when isOpen is true', () => {
    wrapper = shallow(<Collapse isOpen />);
    expect(wrapper.state('dimension')).toBe(null);
  });

  it('should not set height when isOpen is false', () => {
    wrapper = shallow(<Collapse isOpen={false} />);
    expect(wrapper.state('dimension')).toBe(null);
  });

  it('should forward all styles', () => {
    wrapper = mount(<Collapse isOpen style={{ backgroundColor: 'black' }} />);
    expect(wrapper.find('div').prop('style').backgroundColor).toBe('black');
  });

  it('should forward all callbacks', () => {
    const callbacks = {
      onEnter: jest.fn(),
      onEntering: jest.fn(),
      onEntered: jest.fn(),
      onExit: jest.fn(),
      onExiting: jest.fn(),
      onExited: jest.fn(),
    };
    wrapper = mount(<Collapse isOpen={isOpen} {...callbacks} />);
    toggle();
    expect(callbacks.onEnter).toHaveBeenCalled();
    expect(callbacks.onEntering).toHaveBeenCalled();
    expect(callbacks.onEntered).not.toHaveBeenCalled();
    jest.runTimersToTime(350);
    expect(callbacks.onEntered).toHaveBeenCalled();
    expect(callbacks.onExit).not.toHaveBeenCalled();

    toggle();
    expect(callbacks.onExit).toHaveBeenCalled();
    expect(callbacks.onExiting).toHaveBeenCalled();
    expect(callbacks.onExited).not.toHaveBeenCalled();
    jest.runTimersToTime(350);
    expect(callbacks.onExiting).toHaveBeenCalled();
    expect(callbacks.onExited).toHaveBeenCalled();

    wrapper.unmount();
  });

  it('should apply correct bootstrap classes', () => {
    wrapper = mount(<Collapse isOpen={isOpen} />);
    toggle();
    expect(wrapper.update().find('div').prop('className')).toBe('collapsing');
    jest.runTimersToTime(350);
    expect(wrapper.update().find('div').prop('className')).toBe(
      'collapse show',
    );

    toggle();
    expect(wrapper.update().find('div').prop('className')).toBe('collapsing');
    jest.runTimersToTime(350);
    expect(wrapper.update().find('div').prop('className')).toBe('collapse');

    wrapper.unmount();
  });

  it('should set inline style to 0 when isOpen change to false', () => {
    isOpen = true;
    wrapper = mount(<Collapse isOpen={isOpen} />);
    toggle();
    expect(wrapper.state('dimension')).toBe(0);
    wrapper.unmount();
  });

  it('should remove inline style when isOpen change to true after transition', () => {
    wrapper = mount(<Collapse isOpen={isOpen} />);
    toggle();
    jest.runTimersToTime(380);
    expect(wrapper.state('dimension')).toBe(null);
    wrapper.unmount();
  });
});
<|endoftext|>


<commit_before>function validate_time(time) {
    // either HH:MM:SS, MM:SS, H:MM:SS, or M:SS. Also technically H:M:S but that should parse fine into seconds
    var regex = new RegExp('(\\d{1,2}:)?\\d{1,2}:\\d{2}');
    return regex.test(time);
}

function hhmmss_to_seconds(time) {
    var separated_times = time.split(':')
    var total_seconds = 0;
    if (separated_times.length == 3) {
        // handle hours specially
        hours = parseInt(separated_times.shift(), 10);
        total_seconds += 3600 * hours;
    }
    // now just MM, SS
    minutes = parseInt(separated_times[0], 10)
    seconds = parseInt(separated_times[1], 10);
    if (minutes > 59 || seconds > 59) {
        alert("Invalid time: " + time);
        throw 'invalid time';
    }
    result = total_seconds + (minutes * 60) + seconds;
    if (result == 0) {
        alert("Invalid time: " + time);
        throw 'invalid time';
    }
    return result;
}

function get_new_row(id, mode) {
  var front = get_id_td(id) + get_mode_td(id, mode);

  if (mode == "set") {
    var back = '<input type="text" name="temperature" placeholder="Temperature (°C)">	<input type="text" name="duration" placeholder="Duration (HH:MM:SS)">	';
  };

  if (mode == "linear") {
    var back = '<input type="text" name="start_temperature" placeholder="Start Temperature (°C)">	<input type="text" name="end_temperature" placeholder="End Temperature (°C)">	<input type="text" name="duration" placeholder="Duration (HH:MM:SS)">	;'
  }

  if (mode == "hold") {
    var back = '<input type="text" name="temperature" placeholder="Temperature (°C)">	';
  };

  if (mode == "repeat") {
    var back = '<input type="text" name="num_repeats" placeholder="Number of repeats">	';
  };

  return front + back;
};

function get_id_td(id) {
  return '' + id + '	';
};

function get_mode_td(id, mode) {
  return '<select id="' + id + '" class="mode" name="mode"><option value="set">Set</option><option value="hold">Hold</option><option value="linear">Linear Gradient</option><option value="repeat">Repeat</option></select>	';
};

$(document).ready(function(){

  // generate the first row instead of hard coding it in the HTML so we can guarantee consistency
  var first_row = get_new_row(1, "set");
  $("#temperature_settings tr:first").html(first_row);

  // adds additional rows so any number of instructions can be given to the temperature controller
  $(document.body).on('click', '#add_button' ,function() {
    var new_id = parseInt($("#temperature_settings tr:last").find('td:first').html()) + 1;
    var new_row = '
' + get_new_row(new_id, "set") + '
';
    $("#temperature_settings tr:last").after(new_row);
  });

  http('driver', 'GET', null, function(d){
      options = '<option value="-1">Choose a Driver</option>'
          for (i=0; i<d.length; i++) {
              option = "<option value='" + d[i]['id'] + "'>"
              option += d[i]['name']
              option += "</option>"
              options += option;
          }
      $("#driver").empty().append(options)
  });

  // different modes need different inputs, so we change the elements available in the row to accommodate that
  $(document.body).on('change', '.mode' ,function() {
     var new_row = get_new_row(this.id, this.value);
     var id = this.id;
     var mode = this.value;
     // we're currently in the dropdown element. two levels up gives us the entire row
     $(this).parent().parent().html(new_row);
     $("#" + id).val(mode);
  });

  // validate and save the program
  $(document.body).on('click', '#save' ,function() {
    var program = {};
    var row_id = 0;
    $("#settings").serializeArray().map(function(item) {
      if (item.name == "mode") {
        // we're on a new row (i.e. a new instruction)
        row_id++;
        program[row_id] = {"mode": item.value};
      } else {
        if (item.name == "duration") {
            if (!validate_time(item.value)) {
               alert("Invalid time in step " + row_id + ": " + item.value);
               throw 'Invalid time';
            }
        }

        program[row_id][item.name] = (item.name == "duration" ? hhmmss_to_seconds(item.value) : item.value);
      };
    });
    console.log(program);

    errors = [];
    name = $("#name").val();
    if (name.length == 0) {
        errors.push("You need to enter a name.")
    }
    driver = $("#driver").val();
    if (driver == "-1") {
        errors.push("You need to choose a driver.")
    }
    scientist = get_id('user');
    if (scientist === undefined || scientist < 1) {
        errors.push("You somehow have an invalid scientist ID. Go pick a user first.")
    }
    data = {'steps': JSON.stringify(program),
            'name': name,
            'driver': driver,
            'scientist': scientist}

    // validate program here
    if (errors.length > 0) {
        message = "Your program cannot be saved! "
        for (i=0; i<errors.length; i++) {
            message += " " + errors[i];
        }
        alert(message);
    }
    else {
      http('program', 'POST', data, function(response) {
        //window.location.href = '/program/manage/?id=' + response['id'];
      });
    }
  });
});
<commit_msg>uncomment<commit_after>function validate_time(time) {
    // either HH:MM:SS, MM:SS, H:MM:SS, or M:SS. Also technically H:M:S but that should parse fine into seconds
    var regex = new RegExp('(\\d{1,2}:)?\\d{1,2}:\\d{2}');
    return regex.test(time);
}

function hhmmss_to_seconds(time) {
    var separated_times = time.split(':')
    var total_seconds = 0;
    if (separated_times.length == 3) {
        // handle hours specially
        hours = parseInt(separated_times.shift(), 10);
        total_seconds += 3600 * hours;
    }
    // now just MM, SS
    minutes = parseInt(separated_times[0], 10)
    seconds = parseInt(separated_times[1], 10);
    if (minutes > 59 || seconds > 59) {
        alert("Invalid time: " + time);
        throw 'invalid time';
    }
    result = total_seconds + (minutes * 60) + seconds;
    if (result == 0) {
        alert("Invalid time: " + time);
        throw 'invalid time';
    }
    return result;
}

function get_new_row(id, mode) {
  var front = get_id_td(id) + get_mode_td(id, mode);

  if (mode == "set") {
    var back = '<input type="text" name="temperature" placeholder="Temperature (°C)">	<input type="text" name="duration" placeholder="Duration (HH:MM:SS)">	';
  };

  if (mode == "linear") {
    var back = '<input type="text" name="start_temperature" placeholder="Start Temperature (°C)">	<input type="text" name="end_temperature" placeholder="End Temperature (°C)">	<input type="text" name="duration" placeholder="Duration (HH:MM:SS)">	;'
  }

  if (mode == "hold") {
    var back = '<input type="text" name="temperature" placeholder="Temperature (°C)">	';
  };

  if (mode == "repeat") {
    var back = '<input type="text" name="num_repeats" placeholder="Number of repeats">	';
  };

  return front + back;
};

function get_id_td(id) {
  return '' + id + '	';
};

function get_mode_td(id, mode) {
  return '<select id="' + id + '" class="mode" name="mode"><option value="set">Set</option><option value="hold">Hold</option><option value="linear">Linear Gradient</option><option value="repeat">Repeat</option></select>	';
};

$(document).ready(function(){

  // generate the first row instead of hard coding it in the HTML so we can guarantee consistency
  var first_row = get_new_row(1, "set");
  $("#temperature_settings tr:first").html(first_row);

  // adds additional rows so any number of instructions can be given to the temperature controller
  $(document.body).on('click', '#add_button' ,function() {
    var new_id = parseInt($("#temperature_settings tr:last").find('td:first').html()) + 1;
    var new_row = '
' + get_new_row(new_id, "set") + '
';
    $("#temperature_settings tr:last").after(new_row);
  });

  http('driver', 'GET', null, function(d){
      options = '<option value="-1">Choose a Driver</option>'
          for (i=0; i<d.length; i++) {
              option = "<option value='" + d[i]['id'] + "'>"
              option += d[i]['name']
              option += "</option>"
              options += option;
          }
      $("#driver").empty().append(options)
  });

  // different modes need different inputs, so we change the elements available in the row to accommodate that
  $(document.body).on('change', '.mode' ,function() {
     var new_row = get_new_row(this.id, this.value);
     var id = this.id;
     var mode = this.value;
     // we're currently in the dropdown element. two levels up gives us the entire row
     $(this).parent().parent().html(new_row);
     $("#" + id).val(mode);
  });

  // validate and save the program
  $(document.body).on('click', '#save' ,function() {
    var program = {};
    var row_id = 0;
    $("#settings").serializeArray().map(function(item) {
      if (item.name == "mode") {
        // we're on a new row (i.e. a new instruction)
        row_id++;
        program[row_id] = {"mode": item.value};
      } else {
        if (item.name == "duration") {
            if (!validate_time(item.value)) {
               alert("Invalid time in step " + row_id + ": " + item.value);
               throw 'Invalid time';
            }
        }

        program[row_id][item.name] = (item.name == "duration" ? hhmmss_to_seconds(item.value) : item.value);
      };
    });
    console.log(program);

    errors = [];
    name = $("#name").val();
    if (name.length == 0) {
        errors.push("You need to enter a name.")
    }
    driver = $("#driver").val();
    if (driver == "-1") {
        errors.push("You need to choose a driver.")
    }
    scientist = get_id('user');
    if (scientist === undefined || scientist < 1) {
        errors.push("You somehow have an invalid scientist ID. Go pick a user first.")
    }
    data = {'steps': JSON.stringify(program),
            'name': name,
            'driver': driver,
            'scientist': scientist}

    // validate program here
    if (errors.length > 0) {
        message = "Your program cannot be saved! "
        for (i=0; i<errors.length; i++) {
            message += " " + errors[i];
        }
        alert(message);
    }
    else {
      http('program', 'POST', data, function(response) {
          window.location.href = '/program/manage/?id=' + response['id'];
      });
    }
  });
});
<|endoftext|>


<commit_before>export { AsyncWorker_processingId_Resulter_Map as processingId_Resulter_Map };

import { Resulter } from "./AsyncWorker_Resulter.js";
import { PromiseResolveReject } from "./AsyncWorker_PromiseResolveReject.js";

/**
 * A collection of AsyncWorker.Resulter by processingId as key.
 */
class AsyncWorker_processingId_Resulter_Map {

  /** */
  constructor() {
    this.map = new Map();
  }

  get size() {
    return this.map.size;
  }

  /** */
  clear() {
    this.map.clear();
  }

  /**
   * Create a new AsyncWorker.Resulter. Record it in this map by processingId
   * as key.
   *
   * This method is the initializer the processingId's PromiseResolveRejectArray.
   *
   * @param {number} processingId
   *   The numeric identifier of the processing.
   *
   * @return {AsyncWorker.Resulter}
   *   Return an async generator for receving result from WorkerBody of the processing.
   */
  createResulter_by_processingId( processingId ) {
    let resulter = new Resulter( processingId, this );

    let thePromiseResolveReject = new PromiseResolveReject( processingId );
    resulter.PromiseResolveRejectArray.push( thePromiseResolveReject );

    this.map.set( processingId, resulter );

    return resulter;
  }

  /**
   *
   * If the (not pending; fulfilled) promise was resolved to ( done == true )
   * or rejected, there will be no more result received from the WorkerBody
   * in the future. So remove the resulter and its entire result queue (i.e.
   * PromiseResolveRejectArray) of the processing.
   *
   *
   * Note: Both the following two codes handle resulter removing (according to
   * which one happen last):
   *   - AsyncWorker_Resulter.next()
   *   - AsyncWorker_processingId_Resulter_Map
   *       .resolve_or_reject_by_processingId_done_value()
   *
   * @param {AsyncWork_PromiseResolveReject} thePromiseResolveReject
   *   The promise to be checked whether is final.
   */
  removeResulter_by_PromiseResolveReject_final( aPromiseResolveReject ) {
    if (   ( aPromiseResolveReject.final )
        && ( aPromiseResolveReject.hasBeenYielded_byResulter )
       ) {
      this.map.delete( aPromiseResolveReject.processingId );
    }
  }

  /**
   * @param {number} processingId
   *   The numeric identifier of the processing.
   *
   * @return {AsyncWorker_Resulter}
   *   Return the resulter of the processing.
   */
  getResulter_by_processingId( processingId ) {
    let resulter = this.map.get( processingId );
    return resulter;
  }

  /**
   * Suppose every method function of WorkerProxy is an async generator.
   *
   * When WorkerProxy receives [ processingId, done, value ] object from WorkerBody,
   * please call this method. It will resolve or reject the corresponding pending
   * promise.
   *
   *   - if ( done == undefind ), reject the pending PromiseResolveReject.
   *
   *   - if ( done == true ), resolve the pending PromiseResolveReject.
   *
   *   - if ( done == false ), resolve the pending PromiseResolveReject. And
   *       append a new pending PromiseResolveReject  for waiting future result
   *       from WorkerBody.
   *
   * This method is the producer the processingId's PromiseResolveRejectArray.
   *
   *
   * @param {number} processingId
   *   The numeric identifier of the processing.
   *
   * @param {boolean} done
   *   If true, this is the final value of the processing. If false, there will be
   * more result values coming from the WorkerBody. If undfined, the WorkerBody is
   * failed to execute the processing.
   *
   * @param {any} value
   *   The result value of this step of the processing. If ( done == undefined ),
   * this value represents errorReason.
   */
  resolve_or_reject_by_processingId_done_value( processingId, done, value ) {
    let resulter = this.getResulter_by_processingId( processingId );
    if ( !resulter )
      throw Error(
          `AsyncWorker.processingId_Resulter_Map.resolve_by_processingId_done_value(): `
        + `processingId=${processingId}. `
        + `The resulter does not exist.`
      );

    if ( resulter.PromiseResolveRejectArray.length <= 0 )
      throw Error(
          `AsyncWorker.processingId_Resulter_Map.resolve_by_processingId_done_value(): `
        + `processingId=${processingId}. `
        + `The resulter.PromiseResolveRejectArray should not be empty.`
      );

    // Always resolve the last promise. (Assume it is pending.)
    let lastArrayIndex = resulter.PromiseResolveRejectArray.length - 1;
    let currentPromiseResolveReject = resulter.PromiseResolveRejectArray[ lastArrayIndex ];

    if ( !currentPromiseResolveReject.pending )
      throw Error(
          `AsyncWorker.processingId_Resulter_Map.resolve_by_processingId_done_value(): `
        + `processingId=${processingId}, lastArrayIndex=${lastArrayIndex}. `
        + `The last element of PromiseResolveRejectArray should be pending.`
      );

    // 1. If the done is undefined, it means "reject". (i.e. neither false nor true).
    if ( done == undefined ) {

      // 1.1 Reject the current pending promise to the errorReason.
      //     (In this case, the value represents errorReason.)
      currentPromiseResolveReject.errorReason_reject( value );

    // 2. Otherwise, it is a regular result message (i.e. either false (not done) or
    //    true (done)).
    } else {

      // 2.1 Prepare next pending promise.

      // 2.1.1 Since web worker says the processing is done, do not create any more
      //       pending promise because the processing will have no more result coming
      //       from web worker in the future.
      if ( done ) {
        // Do nothing.

      // 2.1.2 The web worker says the processing is not yet completed, create a new
      //       pending promise for the same processing for waiting future result from
      //       web worker.
      } else {
        let nextPromiseResolveReject = new PromiseResolveReject( processingId );
        resulter.PromiseResolveRejectArray.push( nextPromiseResolveReject );
      }

      // 2.2 Resolve the current pending promise to the specified value.
      currentPromiseResolveReject.done_value_resolve( done, value );
    }

    // 3. Handle final promise.
    this.removeResulter_by_PromiseResolveReject_final( currentPromiseResolveReject );
  }

  /**
   * Reject all pending PromiseResolveReject.
   *
   * This is usually used when an AsyncWorker will be terminated forcibly. Rejecting
   * these pending promises could avoid the promises awaiter be blocked forever.
   *
   * @param {any} errorReason
   *   The information of the rejecting.
   */
  reject_all_pending_by_errorReason( errorReason ) {

    for ( let resulter of this.getResulter_by_processingId.values() ) {

//!!! ...unfinished... (2022/09/26)
//should reject all pending Resulter.

      if ( resulter.PromiseResolveRejectArray.length <= 0 )
        continue;

      // Always reject the last promise, because it is the only one promise which
      // is possible still pending.
      let lastArrayIndex = resulter.PromiseResolveRejectArray.length - 1;
      let currentPromiseResolveReject
        = resulter.PromiseResolveRejectArray[ lastArrayIndex ];

      if ( !currentPromiseResolveReject.pending )
          continue;

      // Reject the current pending promise to the errorReason.
      currentPromiseResolveReject.errorReason_reject( errorReason );

//!!! ??? remove during visiting?
      // 3. Handle final promise.
      this.removeResulter_by_PromiseResolveReject_final( currentPromiseResolveReject );
    }

  }

}
<commit_msg>reject_all_pending_by_errorReason<commit_after>export { AsyncWorker_processingId_Resulter_Map as processingId_Resulter_Map };

import { Resulter } from "./AsyncWorker_Resulter.js";
import { PromiseResolveReject } from "./AsyncWorker_PromiseResolveReject.js";

/**
 * A collection of AsyncWorker.Resulter by processingId as key.
 */
class AsyncWorker_processingId_Resulter_Map {

  /** */
  constructor() {
    this.map = new Map();
  }

  get size() {
    return this.map.size;
  }

  /** */
  clear() {
    this.map.clear();
  }

  /**
   * Create a new AsyncWorker.Resulter. Record it in this map by processingId
   * as key.
   *
   * This method is the initializer the processingId's PromiseResolveRejectArray.
   *
   * @param {number} processingId
   *   The numeric identifier of the processing.
   *
   * @return {AsyncWorker.Resulter}
   *   Return an async generator for receving result from WorkerBody of the processing.
   */
  createResulter_by_processingId( processingId ) {
    let resulter = new Resulter( processingId, this );

    let thePromiseResolveReject = new PromiseResolveReject( processingId );
    resulter.PromiseResolveRejectArray.push( thePromiseResolveReject );

    this.map.set( processingId, resulter );

    return resulter;
  }

  /**
   *
   * If the (not pending; fulfilled) promise was resolved to ( done == true )
   * or rejected, there will be no more result received from the WorkerBody
   * in the future. So remove the resulter and its entire result queue (i.e.
   * PromiseResolveRejectArray) of the processing.
   *
   *
   * Note: Both the following two codes handle resulter removing (according to
   * which one happen last):
   *   - AsyncWorker_Resulter.next()
   *   - AsyncWorker_processingId_Resulter_Map
   *       .resolve_or_reject_by_processingId_done_value()
   *
   * @param {AsyncWork_PromiseResolveReject} thePromiseResolveReject
   *   The promise to be checked whether is final.
   */
  removeResulter_by_PromiseResolveReject_final( aPromiseResolveReject ) {
    if (   ( aPromiseResolveReject.final )
        && ( aPromiseResolveReject.hasBeenYielded_byResulter )
       ) {
      this.map.delete( aPromiseResolveReject.processingId );
    }
  }

  /**
   * @param {number} processingId
   *   The numeric identifier of the processing.
   *
   * @return {AsyncWorker_Resulter}
   *   Return the resulter of the processing.
   */
  getResulter_by_processingId( processingId ) {
    let resulter = this.map.get( processingId );
    return resulter;
  }

  /**
   * Suppose every method function of WorkerProxy is an async generator.
   *
   * When WorkerProxy receives [ processingId, done, value ] object from WorkerBody,
   * please call this method. It will resolve or reject the corresponding pending
   * promise.
   *
   *   - if ( done == undefind ), reject the pending PromiseResolveReject.
   *
   *   - if ( done == true ), resolve the pending PromiseResolveReject.
   *
   *   - if ( done == false ), resolve the pending PromiseResolveReject. And
   *       append a new pending PromiseResolveReject  for waiting future result
   *       from WorkerBody.
   *
   * This method is the producer the processingId's PromiseResolveRejectArray.
   *
   *
   * @param {number} processingId
   *   The numeric identifier of the processing.
   *
   * @param {boolean} done
   *   If true, this is the final value of the processing. If false, there will be
   * more result values coming from the WorkerBody. If undfined, the WorkerBody is
   * failed to execute the processing.
   *
   * @param {any} value
   *   The result value of this step of the processing. If ( done == undefined ),
   * this value represents errorReason.
   */
  resolve_or_reject_by_processingId_done_value( processingId, done, value ) {
    let resulter = this.getResulter_by_processingId( processingId );
    if ( !resulter )
      throw Error(
          `AsyncWorker.processingId_Resulter_Map.resolve_by_processingId_done_value(): `
        + `processingId=${processingId}. `
        + `The resulter does not exist.`
      );

    if ( resulter.PromiseResolveRejectArray.length <= 0 )
      throw Error(
          `AsyncWorker.processingId_Resulter_Map.resolve_by_processingId_done_value(): `
        + `processingId=${processingId}. `
        + `The resulter.PromiseResolveRejectArray should not be empty.`
      );

    // Always resolve the last promise. (Assume it is pending.)
    let lastArrayIndex = resulter.PromiseResolveRejectArray.length - 1;
    let currentPromiseResolveReject = resulter.PromiseResolveRejectArray[ lastArrayIndex ];

    if ( !currentPromiseResolveReject.pending )
      throw Error(
          `AsyncWorker.processingId_Resulter_Map.resolve_by_processingId_done_value(): `
        + `processingId=${processingId}, lastArrayIndex=${lastArrayIndex}. `
        + `The last element of PromiseResolveRejectArray should be pending.`
      );

    // 1. If the done is undefined, it means "reject". (i.e. neither false nor true).
    if ( done == undefined ) {

      // 1.1 Reject the current pending promise to the errorReason.
      //     (In this case, the value represents errorReason.)
      currentPromiseResolveReject.errorReason_reject( value );

    // 2. Otherwise, it is a regular result message (i.e. either false (not done) or
    //    true (done)).
    } else {

      // 2.1 Prepare next pending promise.

      // 2.1.1 Since web worker says the processing is done, do not create any more
      //       pending promise because the processing will have no more result coming
      //       from web worker in the future.
      if ( done ) {
        // Do nothing.

      // 2.1.2 The web worker says the processing is not yet completed, create a new
      //       pending promise for the same processing for waiting future result from
      //       web worker.
      } else {
        let nextPromiseResolveReject = new PromiseResolveReject( processingId );
        resulter.PromiseResolveRejectArray.push( nextPromiseResolveReject );
      }

      // 2.2 Resolve the current pending promise to the specified value.
      currentPromiseResolveReject.done_value_resolve( done, value );
    }

    // 3. Handle final promise.
    this.removeResulter_by_PromiseResolveReject_final( currentPromiseResolveReject );
  }

  /**
   * Reject all pending PromiseResolveReject.
   *
   * This is usually used when an AsyncWorker will be terminated forcibly. Rejecting
   * these pending promises could avoid the promises awaiter be blocked forever.
   *
   * @param {any} errorReason
   *   The information of the rejecting.
   */
  reject_all_pending_by_errorReason( errorReason ) {
    for ( let resulter of this.getResulter_by_processingId.values() ) {
      if ( resulter.PromiseResolveRejectArray.length <= 0 )
        continue; // No promised could be rejected. (should not happen)

      // Always reject the last promise, because it is the only one promise which
      // is possible still pending.
      let lastArrayIndex = resulter.PromiseResolveRejectArray.length - 1;
      let currentPromiseResolveReject
        = resulter.PromiseResolveRejectArray[ lastArrayIndex ];

      if ( !currentPromiseResolveReject.pending )
        continue; // A fulfilled promised can not be rejected.

      // Reject the current pending promise to the errorReason.
      currentPromiseResolveReject.errorReason_reject( errorReason );

      // Handle final promise.
      this.removeResulter_by_PromiseResolveReject_final( currentPromiseResolveReject );
    }
  }

}
<|endoftext|>


<commit_before>app.constant("LISTING_ENDPOINT", "php/api/listing/");
app.service("ListingService", function($http,LISTING_ENDPOINT) {
	//INTERNAL FUNCTION FOR HOLDING THE URL
	function getUrl() {
		return(LISTING_ENDPOINT);
	}

	//internal function for tracking the id for the URL
	function getUrlForId(listingId) {
			return(getUrl() + listingId);
	}

	//getting all
	this.all = function() {
		return($hrrp.get(getUrl()));
	};

	//get by id
	this.fetch = function(listingId) {
		return($http.get(getUrlForId(listingid)));
	};

	//get by organization; orgId
	this.fetchOrganization = function(orgId) {
		return($http.get(getUrl() + "?organization=" + orgId));
	};

	//get by Listing post Time; listingPostTime
	this.fetch = function(listingPostTime) {
		return($http.get(getUrl() + "?listingPostTime=" + listingPostTime));
	};

	//get by Listing Parent Id; listing
	this.fetch = function(listingParentId) {
		return($http.get(getUrl() + "?listingParentId=" + listingParentId));
	};

	//get by Listing Type Id;
	this.fetch = function(listingTypeId) {
		return($http.get(getUrl() + "?listingTypeId=" + listingTypeId));
	};

	//post
	this.create = function(listing) {
		return($http.post(getUrl(), listing));
	};

	//put
	this.update = function(listingId, listing){
		return($http.put(getUrlForId(listingId), listing));
	};

	//delete
	this.destroy = function(listingId) {
		return($http.delete(getUrlForId(listingId)));
	};
});
<commit_msg>corrected order of gets and fixed syntax errors (listing-service.js)---->https://app.asana.com/0/60990639151493/70723740973486<commit_after>app.constant("LISTING_ENDPOINT", "php/api/listing/");
app.service("ListingService", function($http,LISTING_ENDPOINT) {
	//INTERNAL FUNCTION FOR HOLDING THE URL
	function getUrl() {
		return(LISTING_ENDPOINT);
	}

	//internal function for tracking the id for the URL
	function getUrlForId(listingId) {
			return(getUrl() + listingId);
	}

	//getting all
	this.all = function() {
		return($hrrp.get(getUrl()));
	};

	//get by id
	this.fetch = function(listingId) {
		return($http.get(getUrlForId(listingid)));
	};

	//get by organization; orgId
	this.fetchOrganization = function(orgId) {
		return($http.get(getUrl() + "?organization=" + orgId));
	};

	//get by Listing Parent Id; listing
	this.fetch = function(listingParentId) {
		return($http.get(getUrl() + "?listingParentId=" + listingParentId));
	};

	//get by Listing post Time; listingPostTime
	this.fetch = function(listingPostTime) {
		return($http.get(getUrl() + "?listingPostTime=" + listingPostTime));
	};

	//get by Listing Type Id;
	this.fetch = function(listingTypeId) {
		return($http.get(getUrl() + "?listingTypeId=" + listingTypeId));
	};

	//post
	this.create = function(listing) {
		return($http.post(getUrl(), listing));
	};

	//put
	this.update = function(listingId, listing){
		return($http.put(getUrlForId(listingId), listing));
	};

	//delete
	this.destroy = function(listingId) {
		return($http.delete(getUrlForId(listingId)));
	};
});
<|endoftext|>


<commit_before>var
    sys = require('sys'),
    path = require('path'),
    http = require('http'),
    paperboy = require('paperboy'),
    nowjs = require('now'),
    uuid = require('uuid');

var webroot = path.join(path.dirname(__filename), 'web');

server = http.createServer(function (req, res) {
    paperboy.deliver(webroot, req, res);
});

var everyone = nowjs.initialize(server);
var chatrooms = {};

var BACKLOG_SIZE = 100;

function backlog_append(room, clientId, nick, type, data) {
    data = data || {};
    data.type = type;
    data.clientId = clientId;
    data.nick = nick;
    room.backlog.push(data);
    console.log("Adding to backlog: " + data.type);
    room.backlog = room.backlog.slice(-1 * BACKLOG_SIZE);
}

function backlog_replay(client, room) {
    for (var i in room.backlog) {
        var d = room.backlog[i];
        switch (d.type) {
            case 'join':
                client.now.receiveJoin(d.clientId, d.nick);
                break;
            case 'leave':
                client.now.receiveLeave(d.clientId, d.nick);
                break;
            case 'nick':
                client.now.receiveNickChange(d.clientId, d.old_nick, d.nick);
                break;
            case 'message':
                client.now.receiveMessage(d.clientId, d.nick, d.message);
                break;
            default:
                console.log('Unknown event ' + d.type + ', ignoring');
        }
    }
}

everyone.now.createRoom = function(cb) {
    var room_id = Buffer(uuid.generate('binary')).toString('base64').slice(0, 10);
    var group = nowjs.getGroup(room_id);

    chatrooms[room_id] = {
        group: group,
        backlog: [],
        members: {}
    };

    console.log('New room created: ' + room_id);
    cb(room_id);
}

everyone.now.joinRoom = function(room_id, nick, cb) {
    var r = chatrooms[room_id];
    if (!r) {
        console.log("Client " + this.user.clientId + " tried to open non-existent room " + room_id);
        cb(false);
        return;
    }

    var people = [];
    for (k in r.members)
        people.push(r.members[k]);

    cb(true);
    r.group.addUser(this.user.clientId);
    r.members[this.user.clientId] = nick;

    backlog_replay(this, r);
    r.group.now.receiveJoin(this.user.clientId, nick);
    backlog_append(r, this.user.clientId, nick, 'join');
    console.log('Client ' + this.user.clientId + ' joined the room ' + room_id);

    this.now.receiveNicknameList(people);
};

everyone.now.sendMessage = function(room_id, message) {
    var r = chatrooms[room_id];
    if (!r) return;

    var nick = r.members[this.user.clientId];
    if (nick == undefined) return;

    if (!message) return;

    r.group.now.receiveMessage(this.user.clientId, nick, message);

    console.log('Client ' + this.user.clientId + ' sent message in room ' + room_id);
    backlog_append(r, this.user.clientId, nick, 'message', { message: message });
}

everyone.now.changeNickname = function(room_id, nick) {
    var r = chatrooms[room_id];
    if (!r) return;

    var old_nick = r.members[this.user.clientId];
    if (old_nick == undefined) return;

    r.members[this.user.clientId] = nick;
    r.group.now.receiveNickChange(this.user.clientId, old_nick, nick);

    console.log('Client ' + this.user.clientId + ' changed nickname');
    backlog_append(r, this.user.clientId, nick, 'nick', { old_nick: old_nick });
}

everyone.on('disconnect', function() {
    for (var room_id in chatrooms) {
        var r = chatrooms[room_id];
        var nick = r.members[this.user.clientId];

        if (nick == undefined)
            continue;

        delete r.members[this.user.clientId];
        console.log('Client ' + this.user.clientId + ' left room ' + room_id);

        if (Object.keys(r.members).length > 0) {
            r.group.now.receiveLeave(this.user.clientId, nick);
            backlog_append(r, this.user.clientId, nick, 'leave');
        } else{
            delete chatrooms[room_id];
            console.log('Deleted empty room ' + room_id);
        }
    }
});

server.listen(7070);

<commit_msg>report number of open rooms in the debug log<commit_after>var
    sys = require('sys'),
    path = require('path'),
    http = require('http'),
    paperboy = require('paperboy'),
    nowjs = require('now'),
    uuid = require('uuid');

var webroot = path.join(path.dirname(__filename), 'web');

server = http.createServer(function (req, res) {
    paperboy.deliver(webroot, req, res);
});

var everyone = nowjs.initialize(server);
var chatrooms = {};

var BACKLOG_SIZE = 100;

function backlog_append(room, clientId, nick, type, data) {
    data = data || {};
    data.type = type;
    data.clientId = clientId;
    data.nick = nick;
    room.backlog.push(data);
    console.log("Adding to backlog: " + data.type);
    room.backlog = room.backlog.slice(-1 * BACKLOG_SIZE);
}

function backlog_replay(client, room) {
    for (var i in room.backlog) {
        var d = room.backlog[i];
        switch (d.type) {
            case 'join':
                client.now.receiveJoin(d.clientId, d.nick);
                break;
            case 'leave':
                client.now.receiveLeave(d.clientId, d.nick);
                break;
            case 'nick':
                client.now.receiveNickChange(d.clientId, d.old_nick, d.nick);
                break;
            case 'message':
                client.now.receiveMessage(d.clientId, d.nick, d.message);
                break;
            default:
                console.log('Unknown event ' + d.type + ', ignoring');
        }
    }
}

everyone.now.createRoom = function(cb) {
    var room_id = Buffer(uuid.generate('binary')).toString('base64').slice(0, 10);
    var group = nowjs.getGroup(room_id);

    chatrooms[room_id] = {
        group: group,
        backlog: [],
        members: {}
    };

    console.log('New room created: ' + room_id);
    cb(room_id);
}

everyone.now.joinRoom = function(room_id, nick, cb) {
    var r = chatrooms[room_id];
    if (!r) {
        console.log("Client " + this.user.clientId + " tried to open non-existent room " + room_id);
        cb(false);
        return;
    }

    var people = [];
    for (k in r.members)
        people.push(r.members[k]);

    cb(true);
    r.group.addUser(this.user.clientId);
    r.members[this.user.clientId] = nick;

    backlog_replay(this, r);
    r.group.now.receiveJoin(this.user.clientId, nick);
    backlog_append(r, this.user.clientId, nick, 'join');
    console.log('Client ' + this.user.clientId + ' joined the room ' + room_id);

    this.now.receiveNicknameList(people);
};

everyone.now.sendMessage = function(room_id, message) {
    var r = chatrooms[room_id];
    if (!r) return;

    var nick = r.members[this.user.clientId];
    if (nick == undefined) return;

    if (!message) return;

    r.group.now.receiveMessage(this.user.clientId, nick, message);

    console.log('Client ' + this.user.clientId + ' sent message in room ' + room_id);
    backlog_append(r, this.user.clientId, nick, 'message', { message: message });
}

everyone.now.changeNickname = function(room_id, nick) {
    var r = chatrooms[room_id];
    if (!r) return;

    var old_nick = r.members[this.user.clientId];
    if (old_nick == undefined) return;

    r.members[this.user.clientId] = nick;
    r.group.now.receiveNickChange(this.user.clientId, old_nick, nick);

    console.log('Client ' + this.user.clientId + ' changed nickname');
    backlog_append(r, this.user.clientId, nick, 'nick', { old_nick: old_nick });
}

everyone.on('disconnect', function() {
    for (var room_id in chatrooms) {
        var r = chatrooms[room_id];
        var nick = r.members[this.user.clientId];

        if (nick == undefined)
            continue;

        delete r.members[this.user.clientId];
        console.log('Client ' + this.user.clientId + ' left room ' + room_id);

        if (Object.keys(r.members).length > 0) {
            r.group.now.receiveLeave(this.user.clientId, nick);
            backlog_append(r, this.user.clientId, nick, 'leave');
        } else{
            delete chatrooms[room_id];
            console.log('Deleted empty room ' + room_id);
            console.log('Rooms remaining: ' + Object.keys(chatrooms).length);
        }
    }
});

server.listen(7070);

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
$(function() {
    $(document).ready(function() {

        var failoverepcount = 1;
        var failoversandboxepcount = 1;
        var loadbalanceepcount = 1;
        var loadbalancesandboxepcount = 1;

        $('#form-api-endpoints').ajaxForm({
            success: function() {
                var options = obtainFormMeta('#form-api-endpoints');
                notify({
                    text: 'API endpoint details saved successfully'
                });
            },
            error: function() {
                notify({
                    text: 'Unable to save endpoint details'
                });
            }
        });

        $('input:radio').change(
            function(){
                if($('input:radio:checked').val() == 'inline') {
                    $('.implementation_method_endpoint').css({'display':'none'});
                    $('.api_designer').css({'display':'block'});
                    //$('#prototyped_api').removeClass('hide');
                } else {
                    $('.implementation_method_endpoint').css({'display':'block'});
                    $('.api_designer').css({'display':'none'});
                    //$('#prototyped_api').addClass('hide');
                }
            }
        );

        $('.more-options').click(function(){
            $('.show-more').css({'display':'none'});
            $('.show-less').css({'display':'block'});
            $('#more-options-endpoints').css({'display':'block'});
       });

        $('.less-options').click(function(){
            $('.show-more').css({'display':'block'});
            $('.show-less').css({'display':'none'});
            $('#more-options-endpoints').css({'display':'none'});
       });

        $( "#api-implement-more-security" ).change(function() {
          if($(this).val() == "secured"){
            $('#api-implement-more-credentials').css({'display':'block'});
          }else{
            $('#api-implement-more-credentials').css({'display':'none'});
          }
        });

        var previousClicked = "";
        $('.api-implement-type').click(function(){
            $($(this).attr('value')).slideToggle();
            $($(this).attr('value')).removeClass('hide');
            if(previousClicked !="" && previousClicked != $(this).attr('value')){
                $(previousClicked).slideUp();
            }
            previousClicked=$(this).attr('value');
        });

        $(".implementation_methods").change(function(event){
            //$(".implementation_method").hide();
            $(".implementation_method_"+$(this).val()).show();
        });

        $( "#api-implement-endpoint-type" ).change(function() {
            var endpointType = $(this).val();
          if(endpointType === "http"){
            $('#api-implement-endpoints-http').css({'display':'block'});
            $('#api-implement-endpoints-address').css({'display':'none'});
            $('#api-implement-endpoints-wsdl').css({'display':'none'});
            $('#api-implement-endpoints-failover').css({'display':'none'});
            $('#api-implement-endpoints-load_balance').css({'display':'none'});
          }else if (endpointType === "address"){
            $('#api-implement-endpoints-http').css({'display':'none'});
            $('#api-implement-endpoints-address').css({'display':'block'});
            $('#api-implement-endpoints-wsdl').css({'display':'none'});
            $('#api-implement-endpoints-failover').css({'display':'none'});
            $('#api-implement-endpoints-load_balance').css({'display':'none'});
          }else if (endpointType === "wsdl"){
            $('#api-implement-endpoints-http').css({'display':'none'});
            $('#api-implement-endpoints-address').css({'display':'none'});
            $('#api-implement-endpoints-wsdl').css({'display':'block'});
            $('#api-implement-endpoints-failover').css({'display':'none'});
            $('#api-implement-endpoints-load_balance').css({'display':'none'});
          }else if (endpointType === "failover"){
            $('#api-implement-endpoints-http').css({'display':'none'});
            $('#api-implement-endpoints-address').css({'display':'none'});
            $('#api-implement-endpoints-wsdl').css({'display':'none'});
            $('#api-implement-endpoints-failover').css({'display':'block'});
            $('#api-implement-endpoints-load_balance').css({'display':'none'});
          }else if (endpointType === "load_balance"){
            $('#api-implement-endpoints-http').css({'display':'none'});
            $('#api-implement-endpoints-address').css({'display':'none'});
            $('#api-implement-endpoints-wsdl').css({'display':'none'});
            $('#api-implement-endpoints-failover').css({'display':'none'});
            $('#api-implement-endpoints-load_balance').css({'display':'block'});
          }
        });

        $( "#api-implement-endpoints-load_balance-algoritm" ).change(function() {
          if($(this).val() == "other"){
            $('#api-implement-endpoints-load_balance-algo-div').css({'display':'block'});
          }else{
            $('#api-implement-endpoints-load_balance-algo-div').css({'display':'none'});
          }
        });

        //Failover EP related- START
        $('#prod-failover-endpoint-add-btn').click(function(){
            failoverepcount ++;
            $( "#prod-failover-endpoints" ).append('
Endpoint '+ failoverepcount +')
 <input type ="text" id= "api-implement-endpoints-loadbalance-production-loadbalance-'+ failoverepcount +'">
');
       });

        $('#prod-failover-endpoint-remove-btn').click(function(){
            if(failoverepcount >=1){
               $( "#prod-failover-endpoint-" + failoverepcount ).remove();
               failoverepcount --;
            }
       });

        $('#sandbox-failover-endpoint-add-btn').click(function(){
            failoversandboxepcount ++;
            $( "#sandbox-failover-endpoints" ).append('
Endpoint '+ failoversandboxepcount +')
 <input type ="text" id= "api-implement-endpoints-failover-sandbox-endpoint-'+ failoversandboxepcount +'">
');
       });

        $('#sandbox-failover-endpoint-remove-btn').click(function(){
            if(failoversandboxepcount >=1){
                $( "#sandbox-failover-endpoint-" + failoversandboxepcount ).remove();
                failoversandboxepcount --;
            }
       });
        //Failover EP related- END
        //LB EP related- START
        $('#prod-loadbalance-endpoint-add-btn').click(function(){
            loadbalanceepcount ++;
            $( "#prod-loadbalance-endpoints" ).append('
Endpoint '+ loadbalanceepcount +')
 <input type ="text" id= "api-implement-endpoints-loadbalance-production-loadbalance-'+ loadbalanceepcount +'">
');
       });

        $('#prod-loadbalance-endpoint-remove-btn').click(function(){
            if(loadbalanceepcount >=1){
               $( "#prod-loadbalance-endpoint-" + loadbalanceepcount ).remove();
               loadbalanceepcount --;
            }
       });

        $('#sandbox-loadbalance-endpoint-add-btn').click(function(){
            loadbalancesandboxepcount ++;
            $( "#sandbox-loadbalance-endpoints" ).append('
Endpoint '+ loadbalancesandboxepcount +')
 <input type ="text" id= "api-implement-endpoints-loadbalance-sandbox-endpoint-'+ loadbalancesandboxepcount +'">
');
       });

        $('#sandbox-loadbalance-endpoint-remove-btn').click(function(){
            if(loadbalancesandboxepcount >=1){
                $( "#sandbox-loadbalance-endpoint-" + loadbalancesandboxepcount ).remove();
                loadbalancesandboxepcount --;
            }
       });

        $('#go_to_manage').click(function(e){
            $("body").unbind("api_saved");
            $("body").on("api_saved" , function(e){
              location.href = caramel.context + "/assets/api/manage/"+store.publisher.api.id;
            });
            $("#implement_form").submit();
        });
        //LB EP related- END
        var v = $("#prototype_form").validate({
        submitHandler: function(form) {
        var designer = APIMangerAPI.APIDesigner();
        var endpoint_config = {"production_endpoints":{"url": $("#prototype_endpoint").val(),"config":null},"endpoint_type":"http"}
        $('.swagger').val(JSON.stringify(designer.api_doc));
        $('.prototype_config').val(JSON.stringify(endpoint_config));

        //$('#'+thisID).buttonLoader('start');

        $(form).ajaxSubmit({
            success:function(responseText, statusText, xhr, $form) {
             if (!responseText.error) {
                var designer = APIMangerAPI.APIDesigner();
                designer.saved_api = {};
                designer.saved_api.name = responseText.data.apiName;
                designer.saved_api.version = responseText.data.version;
                designer.saved_api.provider = responseText.data.provider;
               // $('#'+thisID).buttonLoader('stop');
                $( "body" ).trigger( "prototype_saved" );
             } else {
                 if (responseText.message == "timeout") {
                     if (ssoEnabled) {
                         var currentLoc = window.location.pathname;
                         if (currentLoc.indexOf(".jag") >= 0) {
                             location.href = "index.jag";
                         } else {
                             location.href = 'site/pages/index.jag';
                         }
                     } else {
                         jagg.showLogin();
                     }
                 } else {
                     jagg.message({content:responseText.message,type:"error"});
                 }
                 $('#'+thisID).buttonLoader('stop');
             }
            }, dataType: 'json'
        });
        }
    });

    $("#prototyped_api").click(function(e){

        $("body").on("prototype_saved", function(e){
            $("body").unbind("prototype_saved");
                var designer = APIMangerAPI.APIDesigner();
                console.log("prototyped_api pressed body on!!");

                data = {
                    action: "updateStatus",
                    name: designer.saved_api.name,
                    version: designer.saved_api.version,
                    provider: designer.saved_api.provider,
                    status: "PROTOTYPED",
                    publishToGateway: true,
                    requireResubscription: true
                };
                $.ajax({
                           url: caramel.context + '/assets/api/apis/lifecycle?type=api',
                           type: 'POST',
                           data: JSON.stringify(data),
                           contentType: 'application/json',
                           success: function (data) {
                               //BootstrapDialog.alert('Successfully Changed the life cycle state');
                                BootstrapDialog.show({
                                type: BootstrapDialog.TYPE_INFO,
                                title: 'Success',
                                message: 'Successfully deployed as a prototype.',
                                buttons: [{
                                            label: 'OK',
                                            action: function(dialogRef){
                                            dialogRef.close();
                                          }
                                          }]
                                });
                           },
                           error: function (data) {
                               //BootstrapDialog.alert('Error while changing the life cycle state');
                            BootstrapDialog.show({
                                                  type: BootstrapDialog.TYPE_DANGER,
                                                  title: 'Error',
                                                  message: 'Error while deploying as a prototype.',
                                                  buttons: [{
                                                             label: 'OK',
                                                             action: function(dialogRef){
                                                             dialogRef.close();
                                                            }
                                                            }]
                                                  });
                           }
                       });
                /*$.ajax({
                    type: "POST",
                    url: jagg.site.context + "/site/blocks/life-cycles/ajax/life-cycles.jag",
                    data: {
                        action :"updateStatus",
                        name:designer.saved_api.name,
                        version:designer.saved_api.version,
                        provider: designer.saved_api.provider,
                        status: "PROTOTYPED",
                        publishToGateway:true,
                        requireResubscription:true
                    },
                    success: function(responseText){
                        if (!responseText.error) {
                             $("#prototype-success").modal('show');
                        }else{
                             if (responseText.message == "timeout") {
                                 if (ssoEnabled) {
                                     var currentLoc = window.location.pathname;
                                     if (currentLoc.indexOf(".jag") >= 0) {
                                         location.href = "index.jag";
                                     } else {
                                       location.href = 'site/pages/index.jag';
                                     }
                                 } else {
                                     jagg.showLogin();
                                 }
                             } else {
                                 jagg.message({content:responseText.message,type:"error"});
                             }
                        }
                    },
                    dataType: "json"
                });             */
            });
       // $("#prototype_form").submit();
    });

        var v = $("#implement_form").validate({
                                                     contentType : "application/x-www-form-urlencoded;charset=utf-8",
                                                     dataType: "json",
                                                     onkeyup: false,
                                                     submitHandler: function(form) {
                                                         var designer = APIMangerAPI.APIDesigner();
                                                         $('#swagger').val(JSON.stringify(designer.api_doc));
                                                         $('#saveMessage').show();
                                                         $('#saveButtons').hide();

                                                         $(form).ajaxSubmit({
                                                                                success:function(responseText, statusText, xhr, $form){
                                                                                $('#saveMessage').hide();
                                                                                $('#saveButtons').show();
                                                                                if (!responseText.error) {
                                                                                $( "body" ).trigger( "api_saved" );
                                                                                } else {
                                                                                if (responseText.message == "timeout") {
                                                                                if (ssoEnabled) {
                                                                                var currentLoc = window.location.pathname;
                                                                                if (currentLoc.indexOf(".jag") >= 0) {
                                                                                location.href = "index.jag";
                                                                                } else {
                                                                                location.href = 'site/pages/index.jag';
                                                                                }
                                                                                } else {
                                                                                //jagg.showLogin();
                                                                                }
                                                                                } else {
                                                                                //jagg.message({content:responseText.message,type:"error"});
                                                                                }
                                                                                }
                                                                                }, dataType: 'json'
                                                                            });
                                                     }
                                                 });

    });
});

var thisID='';
$('#saveBtn').click(function(e){
    thisID = $(this).attr('id');
});

$('#savePrototypeBtn').click(function(e){
    thisID = $(this).attr('id');
});

/*$('#prototyped_api').click(function(e){
    thisID = $(this).attr('id');
});*/

$('#go_to_manage').click(function(e){
    thisID = $(this).attr('id');
});

<commit_msg>fixed prototyping APIs<commit_after>/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
$(function() {
    $(document).ready(function() {

        var failoverepcount = 1;
        var failoversandboxepcount = 1;
        var loadbalanceepcount = 1;
        var loadbalancesandboxepcount = 1;

        $('#form-api-endpoints').ajaxForm({
            success: function() {
                var options = obtainFormMeta('#form-api-endpoints');
                notify({
                    text: 'API endpoint details saved successfully'
                });
            },
            error: function() {
                notify({
                    text: 'Unable to save endpoint details'
                });
            }
        });

        $('input:radio').change(
            function(){
                if($('input:radio:checked').val() == 'inline') {
                    $('.implementation_method_endpoint').css({'display':'none'});
                    $('.api_designer').css({'display':'block'});
                    //$('#prototyped_api').removeClass('hide');
                } else {
                    $('.implementation_method_endpoint').css({'display':'block'});
                    $('.api_designer').css({'display':'none'});
                    //$('#prototyped_api').addClass('hide');
                }
            }
        );

        $('.more-options').click(function(){
            $('.show-more').css({'display':'none'});
            $('.show-less').css({'display':'block'});
            $('#more-options-endpoints').css({'display':'block'});
       });

        $('.less-options').click(function(){
            $('.show-more').css({'display':'block'});
            $('.show-less').css({'display':'none'});
            $('#more-options-endpoints').css({'display':'none'});
       });

        $( "#api-implement-more-security" ).change(function() {
          if($(this).val() == "secured"){
            $('#api-implement-more-credentials').css({'display':'block'});
          }else{
            $('#api-implement-more-credentials').css({'display':'none'});
          }
        });

        var previousClicked = "";
        $('.api-implement-type').click(function(){
            $($(this).attr('value')).slideToggle();
            $($(this).attr('value')).removeClass('hide');
            if(previousClicked !="" && previousClicked != $(this).attr('value')){
                $(previousClicked).slideUp();
            }
            previousClicked=$(this).attr('value');
        });

        $(".implementation_methods").change(function(event){
            //$(".implementation_method").hide();
            $(".implementation_method_"+$(this).val()).show();
        });

        $( "#api-implement-endpoint-type" ).change(function() {
            var endpointType = $(this).val();
          if(endpointType === "http"){
            $('#api-implement-endpoints-http').css({'display':'block'});
            $('#api-implement-endpoints-address').css({'display':'none'});
            $('#api-implement-endpoints-wsdl').css({'display':'none'});
            $('#api-implement-endpoints-failover').css({'display':'none'});
            $('#api-implement-endpoints-load_balance').css({'display':'none'});
          }else if (endpointType === "address"){
            $('#api-implement-endpoints-http').css({'display':'none'});
            $('#api-implement-endpoints-address').css({'display':'block'});
            $('#api-implement-endpoints-wsdl').css({'display':'none'});
            $('#api-implement-endpoints-failover').css({'display':'none'});
            $('#api-implement-endpoints-load_balance').css({'display':'none'});
          }else if (endpointType === "wsdl"){
            $('#api-implement-endpoints-http').css({'display':'none'});
            $('#api-implement-endpoints-address').css({'display':'none'});
            $('#api-implement-endpoints-wsdl').css({'display':'block'});
            $('#api-implement-endpoints-failover').css({'display':'none'});
            $('#api-implement-endpoints-load_balance').css({'display':'none'});
          }else if (endpointType === "failover"){
            $('#api-implement-endpoints-http').css({'display':'none'});
            $('#api-implement-endpoints-address').css({'display':'none'});
            $('#api-implement-endpoints-wsdl').css({'display':'none'});
            $('#api-implement-endpoints-failover').css({'display':'block'});
            $('#api-implement-endpoints-load_balance').css({'display':'none'});
          }else if (endpointType === "load_balance"){
            $('#api-implement-endpoints-http').css({'display':'none'});
            $('#api-implement-endpoints-address').css({'display':'none'});
            $('#api-implement-endpoints-wsdl').css({'display':'none'});
            $('#api-implement-endpoints-failover').css({'display':'none'});
            $('#api-implement-endpoints-load_balance').css({'display':'block'});
          }
        });

        $( "#api-implement-endpoints-load_balance-algoritm" ).change(function() {
          if($(this).val() == "other"){
            $('#api-implement-endpoints-load_balance-algo-div').css({'display':'block'});
          }else{
            $('#api-implement-endpoints-load_balance-algo-div').css({'display':'none'});
          }
        });

        //Failover EP related- START
        $('#prod-failover-endpoint-add-btn').click(function(){
            failoverepcount ++;
            $( "#prod-failover-endpoints" ).append('
Endpoint '+ failoverepcount +')
 <input type ="text" id= "api-implement-endpoints-loadbalance-production-loadbalance-'+ failoverepcount +'">
');
       });

        $('#prod-failover-endpoint-remove-btn').click(function(){
            if(failoverepcount >=1){
               $( "#prod-failover-endpoint-" + failoverepcount ).remove();
               failoverepcount --;
            }
       });

        $('#sandbox-failover-endpoint-add-btn').click(function(){
            failoversandboxepcount ++;
            $( "#sandbox-failover-endpoints" ).append('
Endpoint '+ failoversandboxepcount +')
 <input type ="text" id= "api-implement-endpoints-failover-sandbox-endpoint-'+ failoversandboxepcount +'">
');
       });

        $('#sandbox-failover-endpoint-remove-btn').click(function(){
            if(failoversandboxepcount >=1){
                $( "#sandbox-failover-endpoint-" + failoversandboxepcount ).remove();
                failoversandboxepcount --;
            }
       });
        //Failover EP related- END
        //LB EP related- START
        $('#prod-loadbalance-endpoint-add-btn').click(function(){
            loadbalanceepcount ++;
            $( "#prod-loadbalance-endpoints" ).append('
Endpoint '+ loadbalanceepcount +')
 <input type ="text" id= "api-implement-endpoints-loadbalance-production-loadbalance-'+ loadbalanceepcount +'">
');
       });

        $('#prod-loadbalance-endpoint-remove-btn').click(function(){
            if(loadbalanceepcount >=1){
               $( "#prod-loadbalance-endpoint-" + loadbalanceepcount ).remove();
               loadbalanceepcount --;
            }
       });

        $('#sandbox-loadbalance-endpoint-add-btn').click(function(){
            loadbalancesandboxepcount ++;
            $( "#sandbox-loadbalance-endpoints" ).append('
Endpoint '+ loadbalancesandboxepcount +')
 <input type ="text" id= "api-implement-endpoints-loadbalance-sandbox-endpoint-'+ loadbalancesandboxepcount +'">
');
       });

        $('#sandbox-loadbalance-endpoint-remove-btn').click(function(){
            if(loadbalancesandboxepcount >=1){
                $( "#sandbox-loadbalance-endpoint-" + loadbalancesandboxepcount ).remove();
                loadbalancesandboxepcount --;
            }
       });

        $('#go_to_manage').click(function(e){
            $("body").unbind("api_saved");
            $("body").on("api_saved" , function(e){
              location.href = caramel.context + "/assets/api/manage/"+store.publisher.api.id;
            });
            $("#implement_form").submit();
        });
        //LB EP related- END
        var v = $("#prototype_form").validate({
        submitHandler: function(form) {
        var designer = APIMangerAPI.APIDesigner();
        var endpoint_config = {"production_endpoints":{"url": $("#prototype_endpoint").val(),"config":null},"endpoint_type":"http"}
        $('.swagger').val(JSON.stringify(designer.api_doc));
        $('.prototype_config').val(JSON.stringify(endpoint_config));

        //$('#'+thisID).buttonLoader('start');

        $(form).ajaxSubmit({
            success:function(responseText, statusText, xhr, $form) {
             if (!responseText.error) {
                var designer = APIMangerAPI.APIDesigner();
                designer.saved_api = {};
                designer.saved_api.name = responseText.attributes.name;
                designer.saved_api.version = responseText.attributes.version;
                designer.saved_api.provider = responseText.attributes.provider;
               // $('#'+thisID).buttonLoader('stop');
                $( "body" ).trigger( "prototype_saved" );
             } else {
                 if (responseText.message == "timeout") {
                     if (ssoEnabled) {
                         var currentLoc = window.location.pathname;
                         if (currentLoc.indexOf(".jag") >= 0) {
                             location.href = "index.jag";
                         } else {
                             location.href = 'site/pages/index.jag';
                         }
                     } else {
                         jagg.showLogin();
                     }
                 } else {
                     jagg.message({content:responseText.message,type:"error"});
                 }
                 $('#'+thisID).buttonLoader('stop');
             }
            }, dataType: 'json'
        });
        }
    });

    $("#prototyped_api").click(function(e){

        $("body").on("prototype_saved", function(e){
            $("body").unbind("prototype_saved");
                var designer = APIMangerAPI.APIDesigner();
                console.log("prototyped_api pressed body on!!");

                data = {
                    action: "updateStatus",
                    name: designer.saved_api.name,
                    version: designer.saved_api.version,
                    provider: designer.saved_api.provider,
                    status: "PROTOTYPED",
                    publishToGateway: true,
                    requireResubscription: true
                };
                $.ajax({
                           url: caramel.context + '/assets/api/apis/lifecycle?type=api',
                           type: 'POST',
                           data: JSON.stringify(data),
                           contentType: 'application/json',
                           success: function (data) {
                               //BootstrapDialog.alert('Successfully Changed the life cycle state');
                                BootstrapDialog.show({
                                type: BootstrapDialog.TYPE_INFO,
                                title: 'Success',
                                message: 'Successfully deployed as a prototype.',
                                buttons: [{
                                            label: 'OK',
                                            action: function(dialogRef){
                                            dialogRef.close();
                                          }
                                          }]
                                });
                           },
                           error: function (data) {
                               //BootstrapDialog.alert('Error while changing the life cycle state');
                            BootstrapDialog.show({
                                                  type: BootstrapDialog.TYPE_DANGER,
                                                  title: 'Error',
                                                  message: 'Error while deploying as a prototype.',
                                                  buttons: [{
                                                             label: 'OK',
                                                             action: function(dialogRef){
                                                             dialogRef.close();
                                                            }
                                                            }]
                                                  });
                           }
                       });
                /*$.ajax({
                    type: "POST",
                    url: jagg.site.context + "/site/blocks/life-cycles/ajax/life-cycles.jag",
                    data: {
                        action :"updateStatus",
                        name:designer.saved_api.name,
                        version:designer.saved_api.version,
                        provider: designer.saved_api.provider,
                        status: "PROTOTYPED",
                        publishToGateway:true,
                        requireResubscription:true
                    },
                    success: function(responseText){
                        if (!responseText.error) {
                             $("#prototype-success").modal('show');
                        }else{
                             if (responseText.message == "timeout") {
                                 if (ssoEnabled) {
                                     var currentLoc = window.location.pathname;
                                     if (currentLoc.indexOf(".jag") >= 0) {
                                         location.href = "index.jag";
                                     } else {
                                       location.href = 'site/pages/index.jag';
                                     }
                                 } else {
                                     jagg.showLogin();
                                 }
                             } else {
                                 jagg.message({content:responseText.message,type:"error"});
                             }
                        }
                    },
                    dataType: "json"
                });             */
            });
       // $("#prototype_form").submit();
    });

        var v = $("#implement_form").validate({
                                                     contentType : "application/x-www-form-urlencoded;charset=utf-8",
                                                     dataType: "json",
                                                     onkeyup: false,
                                                     submitHandler: function(form) {
                                                         var designer = APIMangerAPI.APIDesigner();
                                                         $('#swagger').val(JSON.stringify(designer.api_doc));
                                                         $('#saveMessage').show();
                                                         $('#saveButtons').hide();

                                                         $(form).ajaxSubmit({
                                                                                success:function(responseText, statusText, xhr, $form){
                                                                                $('#saveMessage').hide();
                                                                                $('#saveButtons').show();
                                                                                if (!responseText.error) {
                                                                                $( "body" ).trigger( "api_saved" );
                                                                                } else {
                                                                                if (responseText.message == "timeout") {
                                                                                if (ssoEnabled) {
                                                                                var currentLoc = window.location.pathname;
                                                                                if (currentLoc.indexOf(".jag") >= 0) {
                                                                                location.href = "index.jag";
                                                                                } else {
                                                                                location.href = 'site/pages/index.jag';
                                                                                }
                                                                                } else {
                                                                                //jagg.showLogin();
                                                                                }
                                                                                } else {
                                                                                //jagg.message({content:responseText.message,type:"error"});
                                                                                }
                                                                                }
                                                                                }, dataType: 'json'
                                                                            });
                                                     }
                                                 });

    });
});

var thisID='';
$('#saveBtn').click(function(e){
    thisID = $(this).attr('id');
});

$('#savePrototypeBtn').click(function(e){
    thisID = $(this).attr('id');
});

/*$('#prototyped_api').click(function(e){
    thisID = $(this).attr('id');
});*/

$('#go_to_manage').click(function(e){
    thisID = $(this).attr('id');
});

<|endoftext|>


<commit_before>/* global L */

import Ember from 'ember';
import setLoading from 'mobility-playground/mixins/set-loading';
import xml2js from 'npm:xml2js';
import polylineEncoded from 'npm:polyline-encoded';

export default Ember.Route.extend(setLoading, {
	queryParams: {
		trace: {
			replace: true,
			refreshModel: true
		}
	},

	setupController: function (controller, model) {
		if (controller.get('bbox') !== null){
			var coordinateArray = [];
			var bboxString = controller.get('bbox');
			var tempArray = [];
			var boundsArray = [];

			coordinateArray = bboxString.split(',');

			for (var i = 0; i < coordinateArray.length; i++){
				tempArray.push(parseFloat(coordinateArray[i]));
			}

			var arrayOne = [];
			var arrayTwo = [];
			arrayOne.push(tempArray[1]);
			arrayOne.push(tempArray[0]);
			arrayTwo.push(tempArray[3]);
			arrayTwo.push(tempArray[2]);
			boundsArray.push(arrayOne);
			boundsArray.push(arrayTwo);
			controller.set('leafletBounds', boundsArray);

		}
		controller.set('leafletBbox', controller.get('bbox'));
		this._super(controller, model);
	},

	fixtures: function() {
		let gpxTraces = [
			{
				"name": "half-marathon",
				"display_name": "half marathon",
				"filename": "half-marathon.gpx",
				"costing": "pedestrian",
				"center": [37.787859, -122.454815]
			},
			{
				"name": "short-run",
				"display_name": "short run",
				"filename": "short-run.gpx",
				"costing": "pedestrian",
				"center": [37.7546595, -122.5091065]
			},
			{
				"name": "mountain-bike-1",
				"display_name": "mountain bike 1",
				"filename": "mountain-bike-1.gpx",
				"costing": "bicycle",
				"center": [37.399614, -122.304894]
			},
			{
				"name": "mountain-bike-2",
				"display_name": "mountain bike 2",
				"filename": "mountain-bike-2.gpx",
				"costing": "bicycle",
				"center": [37.399614, -122.304894]
			},
			{
				"name": "mountain-bike-3",
				"display_name": "mountain bike 3",
				"filename": "mountain-bike-3.gpx",
				"costing": "bicycle",
				"center": [37.399614, -122.304894]
			}
		];
		return gpxTraces;
	},

	getLocalGPX: function(gpxTrace) {
		// might want to use RSVP.promise here instead of RSVP.defer
		var deferred = Ember.RSVP.defer();
		var element = document.getElementById('gpxFileUpload');
		var uploadedTrace = element.files[0];
		var reader = new FileReader();
		reader.onload = function(e) {
		  deferred.resolve(e.target.result);
		};
		reader.onerror = function(e) {
			deferred.reject(this);
		}
		reader.readAsText(uploadedTrace);
		return deferred.promise;
	},

	getRemoteGPX: function(gpxTrace) {
		return Ember.$.ajax({
			type: "GET",
			url: 'assets/traces/' + gpxTrace.filename,
		}).then(function(response) {
			// look into xpath to query xml dom
			var s = new XMLSerializer();
			var str = s.serializeToString(response);
			return str;
		})
	},

	getGPXTrace: function(gpxTrace) {
		if (gpxTrace.name == 'user_upload') {
			return this.getLocalGPX(gpxTrace);
		} else {
			return this.getRemoteGPX(gpxTrace);
		}
	},

	model: function(params){
		if (document.getElementById('gpxFileUpload') === null){
			if (params.trace === "user_upload"){
				this.transitionTo('map-matching',  {queryParams: {trace: null}});
			}
		};
		this.store.unloadAll('data/transitland/operator');
		this.store.unloadAll('data/transitland/stop');
		this.store.unloadAll('data/transitland/route');
		this.store.unloadAll('data/transitland/route_stop_pattern');
		// Get the gpxTrace fixture
		var fixtures = this.fixtures();
		var gpxTrace;
		var mapMatchRequests = null;

		var element = document.getElementById('gpxFileUpload');
		if (params.trace != null && params.trace != 'user_upload') {
			for (var i = 0; i < fixtures.length; i++){
				if (fixtures[i].name === params.trace){
					gpxTrace = fixtures[i];
				}
			}
		} else if (element != null) {
			var uploadedTrace = element.files[0];
			if (uploadedTrace != null) {
				fixtures.push({
					"name": "user_upload",
					"display_name": "user upload",
					"filename": "",
					"costing": "pedestrian",
					"center": [37.787859, -122.454815]
				});
				gpxTrace = fixtures[5]
			}
		}

		if (gpxTrace) {
			var mapMatchRequests = this.getGPXTrace(gpxTrace).then(function(response){
				gpxTrace.coordinates = [];
				var gpxObj;
				// 112 & 114 should be rewritten using xpath
				xml2js.parseString(response, function (err, result){
					gpxObj = result.gpx.trk;
				});
				gpxObj[0].trkseg[0].trkpt.map(function(coord){
					gpxTrace.coordinates.push([parseFloat(coord.$.lat),parseFloat(coord.$.lon)]);
				});
				return gpxTrace;
			}).then(function(gpxTrace){
				// Build the trace_route request
				var routeJson = {
					"shape": [],
					"costing": gpxTrace.costing,
					// "shape_match":"walk_or_snap",
					"shape_match": "map_snap",
					// "filters": {"attributes":["edge.names","edge.id","edge.weighted_grade","edge.speed"],"action":"include"}
				};

				gpxTrace.coordinates.map(function(coord){
					routeJson.shape.push({"lat":coord[0],"lon":coord[1]});
				});
				// trace_route request
				return Ember.$.ajax({
					type:"POST",
					url:'https://valhalla.mapzen.com/trace_route?api_key=mapzen-jLrDBSP&',
					data:JSON.stringify(routeJson)
				});
			})
			.then(function(response){
				// encodedPolyline needed for trace_attribute request
				var encodedPolyline = response.trip.legs[0].shape;
				// decodedPolyline needed for rendering trace_route response on map
				var decodedPolyline = L.PolylineUtil.decode(encodedPolyline, 6);

				// Build the trace_attribute request
				var attributesJson = {
					"encoded_polyline": encodedPolyline,
					"costing": gpxTrace.costing,
					"shape_match": "walk_or_snap",
					// "filters":{"attributes":["edge.weighted_grade", "shape"],"action":"include"}
				};
				var attributesRequest = Ember.$.ajax({
					type: "POST",
					url:'https://valhalla.mapzen.com/trace_attributes?api_key=mapzen-jLrDBSP&',
					data: JSON.stringify(attributesJson)
				});
				return Ember.RSVP.hash({
					decodedPolyline: decodedPolyline,
					attributesRequest: attributesRequest
				});
			});
		}
    // Issue promise with both gpxTrace model and trace_route request
		return Ember.RSVP.hash({
			gpxTraces: fixtures,
			gpxTrace: gpxTrace,
			mapMatchRequests: mapMatchRequests
		})
		// .then(function(r){
		// 	return r
		// });
	},

	actions: {
	}
});<commit_msg>test taking out XML serializer, as response is returned as a string<commit_after>/* global L */

import Ember from 'ember';
import setLoading from 'mobility-playground/mixins/set-loading';
import xml2js from 'npm:xml2js';
import polylineEncoded from 'npm:polyline-encoded';

export default Ember.Route.extend(setLoading, {
	queryParams: {
		trace: {
			replace: true,
			refreshModel: true
		}
	},

	setupController: function (controller, model) {
		if (controller.get('bbox') !== null){
			var coordinateArray = [];
			var bboxString = controller.get('bbox');
			var tempArray = [];
			var boundsArray = [];

			coordinateArray = bboxString.split(',');

			for (var i = 0; i < coordinateArray.length; i++){
				tempArray.push(parseFloat(coordinateArray[i]));
			}

			var arrayOne = [];
			var arrayTwo = [];
			arrayOne.push(tempArray[1]);
			arrayOne.push(tempArray[0]);
			arrayTwo.push(tempArray[3]);
			arrayTwo.push(tempArray[2]);
			boundsArray.push(arrayOne);
			boundsArray.push(arrayTwo);
			controller.set('leafletBounds', boundsArray);

		}
		controller.set('leafletBbox', controller.get('bbox'));
		this._super(controller, model);
	},

	fixtures: function() {
		let gpxTraces = [
			{
				"name": "half-marathon",
				"display_name": "half marathon",
				"filename": "half-marathon.gpx",
				"costing": "pedestrian",
				"center": [37.787859, -122.454815]
			},
			{
				"name": "short-run",
				"display_name": "short run",
				"filename": "short-run.gpx",
				"costing": "pedestrian",
				"center": [37.7546595, -122.5091065]
			},
			{
				"name": "mountain-bike-1",
				"display_name": "mountain bike 1",
				"filename": "mountain-bike-1.gpx",
				"costing": "bicycle",
				"center": [37.399614, -122.304894]
			},
			{
				"name": "mountain-bike-2",
				"display_name": "mountain bike 2",
				"filename": "mountain-bike-2.gpx",
				"costing": "bicycle",
				"center": [37.399614, -122.304894]
			},
			{
				"name": "mountain-bike-3",
				"display_name": "mountain bike 3",
				"filename": "mountain-bike-3.gpx",
				"costing": "bicycle",
				"center": [37.399614, -122.304894]
			}
		];
		return gpxTraces;
	},

	getLocalGPX: function(gpxTrace) {
		// might want to use RSVP.promise here instead of RSVP.defer
		var deferred = Ember.RSVP.defer();
		var element = document.getElementById('gpxFileUpload');
		var uploadedTrace = element.files[0];
		var reader = new FileReader();
		reader.onload = function(e) {
		  deferred.resolve(e.target.result);
		};
		reader.onerror = function(e) {
			deferred.reject(this);
		}
		reader.readAsText(uploadedTrace);
		return deferred.promise;
	},

	getRemoteGPX: function(gpxTrace) {
		return Ember.$.ajax({
			type: "GET",
			url: 'assets/traces/' + gpxTrace.filename,
		})
		// .then(function(response) {
			// look into xpath to query xml dom
			// var s = new XMLSerializer();
			// var str = s.serializeToString(response);
			// return str;
		// })
	},

	getGPXTrace: function(gpxTrace) {
		if (gpxTrace.name == 'user_upload') {
			return this.getLocalGPX(gpxTrace);
		} else {
			return this.getRemoteGPX(gpxTrace);
		}
	},

	model: function(params){
		if (document.getElementById('gpxFileUpload') === null){
			if (params.trace === "user_upload"){
				this.transitionTo('map-matching',  {queryParams: {trace: null}});
			}
		};
		this.store.unloadAll('data/transitland/operator');
		this.store.unloadAll('data/transitland/stop');
		this.store.unloadAll('data/transitland/route');
		this.store.unloadAll('data/transitland/route_stop_pattern');
		// Get the gpxTrace fixture
		var fixtures = this.fixtures();
		var gpxTrace;
		var mapMatchRequests = null;

		var element = document.getElementById('gpxFileUpload');
		if (params.trace != null && params.trace != 'user_upload') {
			for (var i = 0; i < fixtures.length; i++){
				if (fixtures[i].name === params.trace){
					gpxTrace = fixtures[i];
				}
			}
		} else if (element != null) {
			var uploadedTrace = element.files[0];
			if (uploadedTrace != null) {
				fixtures.push({
					"name": "user_upload",
					"display_name": "user upload",
					"filename": "",
					"costing": "pedestrian",
					"center": [37.787859, -122.454815]
				});
				gpxTrace = fixtures[5]
			}
		}

		if (gpxTrace) {
			var mapMatchRequests = this.getGPXTrace(gpxTrace).then(function(response){
				gpxTrace.coordinates = [];
				var gpxObj;
				// 112 & 114 should be rewritten using xpath
				xml2js.parseString(response, function (err, result){
					gpxObj = result.gpx.trk;
				});
				gpxObj[0].trkseg[0].trkpt.map(function(coord){
					gpxTrace.coordinates.push([parseFloat(coord.$.lat),parseFloat(coord.$.lon)]);
				});
				return gpxTrace;
			}).then(function(gpxTrace){
				// Build the trace_route request
				var routeJson = {
					"shape": [],
					"costing": gpxTrace.costing,
					// "shape_match":"walk_or_snap",
					"shape_match": "map_snap",
					// "filters": {"attributes":["edge.names","edge.id","edge.weighted_grade","edge.speed"],"action":"include"}
				};

				gpxTrace.coordinates.map(function(coord){
					routeJson.shape.push({"lat":coord[0],"lon":coord[1]});
				});
				// trace_route request
				return Ember.$.ajax({
					type:"POST",
					url:'https://valhalla.mapzen.com/trace_route?api_key=mapzen-jLrDBSP&',
					data:JSON.stringify(routeJson)
				});
			})
			.then(function(response){
				// encodedPolyline needed for trace_attribute request
				var encodedPolyline = response.trip.legs[0].shape;
				// decodedPolyline needed for rendering trace_route response on map
				var decodedPolyline = L.PolylineUtil.decode(encodedPolyline, 6);

				// Build the trace_attribute request
				var attributesJson = {
					"encoded_polyline": encodedPolyline,
					"costing": gpxTrace.costing,
					"shape_match": "walk_or_snap",
					// "filters":{"attributes":["edge.weighted_grade", "shape"],"action":"include"}
				};
				var attributesRequest = Ember.$.ajax({
					type: "POST",
					url:'https://valhalla.mapzen.com/trace_attributes?api_key=mapzen-jLrDBSP&',
					data: JSON.stringify(attributesJson)
				});
				return Ember.RSVP.hash({
					decodedPolyline: decodedPolyline,
					attributesRequest: attributesRequest
				});
			});
		}
    // Issue promise with both gpxTrace model and trace_route request
		return Ember.RSVP.hash({
			gpxTraces: fixtures,
			gpxTrace: gpxTrace,
			mapMatchRequests: mapMatchRequests
		})
		// .then(function(r){
		// 	return r
		// });
	},

	actions: {
	}
});<|endoftext|>


<commit_before>var check = require("../../lib/weixin/checkToken");
var bodyParser = require('body-parser')
	// create application/json parser
var jsonParser = bodyParser.json()
	// create application/x-www-form-urlencoded parser

var urlencodedParser = bodyParser.urlencoded({
	extended: false
})

module.exports = function(req, res, cb) { //微信校验
	var now = new Date();
	console.log("method", req.method);
	console.log(now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + " " + now.getMilliseconds());

	var support_get_flag = true; //调试标记

	if (req.method == "GET" && support_get_flag) {
		var query = req.query;

		var signature = query.signature;
		var timestamp = query.timestamp;
		var nonce = query.nonce;
		var echostr = query.echostr;

		console.log("wexin check", req.query);
		var result = check(signature, timestamp, nonce, echostr);
		console.log("check result=[" + result + "]");
		if (result) {
			return echostr; //如果校验通过 按照微信要求 原样返回echostr
		} else {
			return false;
		}
	} else {
		console.log("headers", req.headers);
		console.log("body", req.body);

		res.header('Content-Type', 'text/xml');

		var result = "";
		result += '<?xml version="1.0" encoding="utf-8"?>';
		var xml=req.body.xml||{};
		result += "<data>";
		result += "<ToUserName><![CDATA[" + xml.tousername + "]]></ToUserName>";
		result += "<FromUserName><![CDATA[" + xml.fromusername + "]]></FromUserName>";
		result += "<CreateTime>" + xml.createtime + "</CreateTime>";
		result += "<MsgType><![CDATA[text]]></MsgType>";
		result += "<Content><![CDATA[你好,测试被动推送消息]]></Content>";
		result += "</data>";

		console.log("return content:",result);
		return result;
	}
	//return result;
}<commit_msg>万恶的数据格式啊<commit_after>var check = require("../../lib/weixin/checkToken");
var bodyParser = require('body-parser')
	// create application/json parser
var jsonParser = bodyParser.json()
	// create application/x-www-form-urlencoded parser

var urlencodedParser = bodyParser.urlencoded({
	extended: false
})

module.exports = function(req, res, cb) { //微信校验
	var now = new Date();
	console.log("method", req.method);
	console.log(now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + " " + now.getMilliseconds());

	var support_get_flag = true; //调试标记

	if (req.method == "GET" && support_get_flag) {
		var query = req.query;

		var signature = query.signature;
		var timestamp = query.timestamp;
		var nonce = query.nonce;
		var echostr = query.echostr;

		console.log("wexin check", req.query);
		var result = check(signature, timestamp, nonce, echostr);
		console.log("check result=[" + result + "]");
		if (result) {
			return echostr; //如果校验通过 按照微信要求 原样返回echostr
		} else {
			return false;
		}
	} else {
		console.log("headers", req.headers);
		console.log("body", req.body);

		res.header('Content-Type', 'text/xml');

		var result = "";
		//result += '<?xml version="1.0" encoding="utf-8"?>';
		var xml=req.body.xml||{};
		result += "<xml>";
		result += "<ToUserName><![CDATA[" + xml.tousername + "]]></ToUserName>";
		result += "<FromUserName><![CDATA[" + xml.fromusername + "]]></FromUserName>";
		result += "<CreateTime>" + xml.createtime + "</CreateTime>";
		result += "<MsgType><![CDATA[text]]></MsgType>";
		result += "<Content><![CDATA[你好,测试被动推送消息]]></Content>";
		result += "</xml>";

		console.log("return content:",result);
		return result;
	}
	//return result;
}<|endoftext|>