<commit_before>const LocatorUtils = require('@routr/location/utils')
const { isLocalnet } = require('@routr/core/ip_util')
const { equalsIgnoreCase, fixPort } = require('@routr/utils/misc_utils')
const config = require('@routr/core/config_util')()
const { RoutingType } = require('@routr/core/routing_type')

const Request = Java.type('javax.sip.message.Request')
const ContactHeader = Java.type('javax.sip.header.ContactHeader')
const RouteHeader = Java.type('javax.sip.header.RouteHeader')
const CSeqHeader = Java.type('javax.sip.header.CSeqHeader')
const ViaHeader = Java.type('javax.sip.header.ViaHeader')
const ToHeader = Java.type('javax.sip.header.ToHeader')
const FromHeader = Java.type('javax.sip.header.FromHeader')
const MaxForwardsHeader = Java.type('javax.sip.header.MaxForwardsHeader')
const SipFactory = Java.type('javax.sip.SipFactory')
const headerFactory = SipFactory.getInstance().createHeaderFactory()
const addressFactory = SipFactory.getInstance().createAddressFactory()

const isExternalDevice = r =>
  r && (!r.sentByAddress || r.sentByAddress.endsWith('.invalid'))
const isWebRTCClient = isExternalDevice
const isPublicAddress = h => !isLocalnet(config.spec.localnets, h)
const needsExternAddress = (route, host) =>
  isExternalDevice(route) || isPublicAddress(host)
const addrHost = a => (a.contains(':') ? a.split(':')[0] : a)
const addrPort = (a, p) => (a.contains(':') ? a.split(':')[1] : p.port)
const ownedAddresss = localAddr =>
  config.spec.externAddr
    ? [
        localAddr,
        {
          host: addrHost(config.spec.externAddr),
          port: addrPort(config.spec.externAddr, localAddr)
        }
      ]
    : [localAddr]
const getAdvertisedAddr = (request, route, localAddr) => {
  // After the initial invite the route object will be null
  // and we need to the the target address from the request uri.
  // If the routing is type IDR the initial request uri will be a local
  // domain and the isLocalnet function will return a wrong result.
  const targetAddr =
    route && route.contactURI
      ? LocatorUtils.aorAsObj(route.contactURI).getHost()
      : request.getRequestURI().getHost()
  const externAddr = config.spec.externAddr
  return config.spec.externAddr && needsExternAddress(route, targetAddr)
    ? { host: addrHost(externAddr), port: addrPort(externAddr, localAddr) }
    : localAddr
}
const getToUser = request => {
  const toHeader = request.getHeader(ToHeader.NAME)
  return toHeader
    .getAddress()
    .getURI()
    .getUser()
}
const getUser = request => request.getRequestURI().getUser()
const configureMaxForwards = request => {
  const requestOut = request.clone()
  const maxForwardsHeader = requestOut.getHeader(MaxForwardsHeader.NAME)
  maxForwardsHeader.decrementMaxForwards()
  return requestOut
}
const configureContact = request => {
  const requestOut = request.clone()
  const contactHeader = requestOut.getHeader(ContactHeader.NAME)
  if (
    contactHeader &&
    config.spec.externAddr &&
    isPublicAddress(requestOut.getRequestURI().getHost())
  ) {
    contactHeader
      .getAddress()
      .getURI()
      .setHost(config.spec.externAddr)
    requestOut.setHeader(contactHeader)
  }
  return requestOut
}
const configureCSeq = request => {
  const requestOut = request.clone()
  // Lower the cseq to match the original request
  if (requestOut.getMethod().equals(Request.INVITE)) {
    const cseq = requestOut.getHeader(CSeqHeader.NAME).getSeqNumber() - 1
    requestOut.getHeader(CSeqHeader.NAME).setSeqNumber(cseq)
  }
  return requestOut
}
const configureProxyAuthorization = request => {
  const requestOut = request.clone()
  requestOut.removeHeader('Proxy-Authorization')
  return requestOut
}
const configureRoute = (request, localAddr) => {
  const requestOut = request.clone()
  const routeHeader = request.getHeader(RouteHeader.NAME)
  if (routeHeader) {
    const host = routeHeader
      .getAddress()
      .getURI()
      .getHost()
    const port = fixPort(
      routeHeader
        .getAddress()
        .getURI()
        .getPort()
    )
    const c = ownedAddresss(localAddr, config.spec.externAddr).filter(
      a => a.host === host && a.port === port
    ).length
    if (c > 0) {
      requestOut.removeFirst(RouteHeader.NAME)
      requestOut.removeFirst(RouteHeader.NAME)
    }
  }
  return requestOut
}
const configureVia = (request, advertisedAddr, route) => {
  const viaHeader = headerFactory.createViaHeader(
    advertisedAddr.host,
    advertisedAddr.port,
    route.transport,
    null
  )
  viaHeader.setRPort()
  const requestOut = request.clone()
  requestOut.addFirst(viaHeader)
  return requestOut
}
const configureRecordRoute = (request, advertisedAddr, localAddr) => {
  const requestOut = request.clone()
  if (config.spec.recordRoute) {
    const p1 = addressFactory.createSipURI(null, localAddr.host)
    p1.setLrParam()
    p1.setPort(localAddr.port)
    const pa1 = addressFactory.createAddress(p1)
    const rr1 = headerFactory.createRecordRouteHeader(pa1)
    requestOut.addHeader(rr1)

    if (config.spec.externAddr && isPublicAddress(advertisedAddr.host)) {
      const p2 = addressFactory.createSipURI(
        null,
        addrHost(config.spec.externAddr)
      )
      p2.setLrParam()
      p2.setPort(addrPort(config.spec.externAddr, localAddr))
      const pa2 = addressFactory.createAddress(p2)
      const rr2 = headerFactory.createRecordRouteHeader(pa2)
      requestOut.addFirst(rr2)
    }
  }
  return requestOut
}
const configureRequestURI = (request, routeInfo, route) => {
  const requestOut = request.clone()
  let uri

  if (
    routeInfo.getRoutingType() === RoutingType.DOMAIN_EGRESS_ROUTING ||
    routeInfo.getRoutingType() === RoutingType.PEER_EGRESS_ROUTING
  ) {
    uri = `sip:${getToUser(request)}@${route.gwHost}`
  } else if (isWebRTCClient(route)) {
    uri = `sip:${getUser(request)}@${route.received}:${route.rport}`
  } else {
    uri = route.contactURI
  }

  requestOut.setRequestURI(LocatorUtils.aorAsObj(uri))
  return requestOut
}
const configurePrivacy = (request, routeInfo) => {
  const requestOut = request.clone()
  requestOut.removeHeader('Privacy')
  const callee = routeInfo.getCallee()
  if (callee && equalsIgnoreCase(callee.kind, 'agent')) {
    let privacyHeader

    if (
      callee.spec.privacy &&
      equalsIgnoreCase(callee.spec.privacy, 'private')
    ) {
      const originFromHeader = requestOut.getHeader(FromHeader.NAME)
      const fromHeaderAddrs = addressFactory.createAddress(
        `"Anonymous" <sip:anonymous@anonymous.invalid>`
      )
      const fromHeader = headerFactory.createHeader(
        'From',
        fromHeaderAddrs.toString()
      )
      fromHeader.setTag(originFromHeader.getTag())
      requestOut.setHeader(fromHeader)
      privacyHeader = headerFactory.createHeader('Privacy', 'id')
    } else {
      privacyHeader = headerFactory.createHeader('Privacy', 'none')
    }

    requestOut.addHeader(privacyHeader)
  }
  return requestOut
}
const configureIdentity = (request, route) => {
  const requestOut = request.clone()
  if (route.thruGw) {
    const remotePartyIdHeader = headerFactory.createHeader(
      'Remote-Party-ID',
      `<sip:${route.number}@${route.gwHost}>;screen=yes;party=calling`
    )
    const dp = requestOut
      .getHeader(FromHeader.NAME)
      .getAddress()
      .getDisplayName()
    const displayName = dp ? `"${dp}" ` : ''
    const pAssertedIdentity = headerFactory.createHeader(
      'P-Asserted-Identity',
      `${displayName}<sip:${route.number}@${route.gwHost}>`
    )
    requestOut.setHeader(remotePartyIdHeader)
    requestOut.setHeader(pAssertedIdentity)
  }
  return requestOut
}
const configureXHeaders = (request, route) => {
  const requestOut = request.clone()
  if (route.thruGw) {
    const gwRefHeader = headerFactory.createHeader('X-Gateway-Ref', route.gwRef)
    requestOut.setHeader(gwRefHeader)
  }
  return requestOut
}
const isInDialog = request =>
  request.getHeader(ToHeader.NAME).getTag() !== null &&
  request.getHeader(FromHeader.NAME).getTag() !== null

module.exports.getAdvertisedAddr = getAdvertisedAddr
module.exports.configureRoute = configureRoute
module.exports.configureVia = configureVia
module.exports.configureProxyAuthorization = configureProxyAuthorization
module.exports.configureRequestURI = configureRequestURI
module.exports.configureMaxForwards = configureMaxForwards
module.exports.configureContact = configureContact
module.exports.configurePrivacy = configurePrivacy
module.exports.configureRecordRoute = configureRecordRoute
module.exports.configureIdentity = configureIdentity
module.exports.configureXHeaders = configureXHeaders
module.exports.configureCSeq = configureCSeq
module.exports.isInDialog = isInDialog
<commit_msg>Refactored<commit_after>const LocatorUtils = require('@routr/location/utils')
const { isLocalnet } = require('@routr/core/ip_util')
const { equalsIgnoreCase, fixPort } = require('@routr/utils/misc_utils')
const config = require('@routr/core/config_util')()
const { RoutingType } = require('@routr/core/routing_type')

const Request = Java.type('javax.sip.message.Request')
const ContactHeader = Java.type('javax.sip.header.ContactHeader')
const RouteHeader = Java.type('javax.sip.header.RouteHeader')
const CSeqHeader = Java.type('javax.sip.header.CSeqHeader')
const ViaHeader = Java.type('javax.sip.header.ViaHeader')
const ToHeader = Java.type('javax.sip.header.ToHeader')
const FromHeader = Java.type('javax.sip.header.FromHeader')
const MaxForwardsHeader = Java.type('javax.sip.header.MaxForwardsHeader')
const SipFactory = Java.type('javax.sip.SipFactory')
const headerFactory = SipFactory.getInstance().createHeaderFactory()
const addressFactory = SipFactory.getInstance().createAddressFactory()

const isExternalDevice = r =>
  r && (!r.sentByAddress || r.sentByAddress.endsWith('.invalid'))
const isWebRTCClient = isExternalDevice
const isPublicAddress = h => !isLocalnet(config.spec.localnets, h)
const needsExternAddress = (route, host) =>
  isExternalDevice(route) || isPublicAddress(host)
const addrHost = a => (a.contains(':') ? a.split(':')[0] : a)
const addrPort = (a, p) => (a.contains(':') ? a.split(':')[1] : p.port)
const ownedAddresss = localAddr =>
  config.spec.externAddr
    ? [
        localAddr,
        {
          host: addrHost(config.spec.externAddr),
          port: addrPort(config.spec.externAddr, localAddr)
        }
      ]
    : [localAddr]
const getAdvertisedAddr = (request, route, localAddr) => {
  // After the initial invite the route object will be null
  // and we need to the the target address from the request uri.
  // If the routing is type IDR the initial request uri will be a local
  // domain and the isLocalnet function will return a wrong result.
  const targetAddr =
    route && route.contactURI
      ? LocatorUtils.aorAsObj(route.contactURI).getHost()
      : request.getRequestURI().getHost()
  const externAddr = config.spec.externAddr
  return config.spec.externAddr && needsExternAddress(route, targetAddr)
    ? { host: addrHost(externAddr), port: addrPort(externAddr, localAddr) }
    : localAddr
}
const getToUser = request => {
  const toHeader = request.getHeader(ToHeader.NAME)
  return toHeader
    .getAddress()
    .getURI()
    .getUser()
}
const getUser = request => request.getRequestURI().getUser()
const configureMaxForwards = request => {
  const requestOut = request.clone()
  const maxForwardsHeader = requestOut.getHeader(MaxForwardsHeader.NAME)
  maxForwardsHeader.decrementMaxForwards()
  return requestOut
}
const configureContact = request => {
  const requestOut = request.clone()
  const contactHeader = requestOut.getHeader(ContactHeader.NAME)
  if (
    contactHeader &&
    config.spec.externAddr &&
    isPublicAddress(requestOut.getRequestURI().getHost())
  ) {
    contactHeader
      .getAddress()
      .getURI()
      .setHost(config.spec.externAddr)
    requestOut.setHeader(contactHeader)
  }
  return requestOut
}
const configureCSeq = request => {
  const requestOut = request.clone()
  // Lower the cseq to match the original request
  if (requestOut.getMethod().equals(Request.INVITE)) {
    const cseq = requestOut.getHeader(CSeqHeader.NAME).getSeqNumber() - 1
    requestOut.getHeader(CSeqHeader.NAME).setSeqNumber(cseq)
  }
  return requestOut
}
const configureProxyAuthorization = request => {
  const requestOut = request.clone()
  requestOut.removeHeader('Proxy-Authorization')
  return requestOut
}
const configureRoute = (request, localAddr) => {
  const requestOut = request.clone()
  const routeHeader = request.getHeader(RouteHeader.NAME)
  if (routeHeader) {
    const host = routeHeader
      .getAddress()
      .getURI()
      .getHost()
    const port = fixPort(
      routeHeader
        .getAddress()
        .getURI()
        .getPort()
    )
    const c = ownedAddresss(localAddr, config.spec.externAddr).filter(
      a => a.host === host && a.port === port
    ).length
    if (c > 0) {
      requestOut.removeFirst(RouteHeader.NAME)
      requestOut.removeFirst(RouteHeader.NAME)
    }
  }
  return requestOut
}
const configureVia = (request, advertisedAddr, transport) => {
  const viaHeader = headerFactory.createViaHeader(
    advertisedAddr.host,
    advertisedAddr.port,
    transport,
    null
  )
  viaHeader.setRPort()
  const requestOut = request.clone()
  requestOut.addFirst(viaHeader)
  return requestOut
}
const configureRecordRoute = (request, advertisedAddr, localAddr) => {
  const requestOut = request.clone()
  if (config.spec.recordRoute) {
    const p1 = addressFactory.createSipURI(null, localAddr.host)
    p1.setLrParam()
    p1.setPort(localAddr.port)
    const pa1 = addressFactory.createAddress(p1)
    const rr1 = headerFactory.createRecordRouteHeader(pa1)
    requestOut.addHeader(rr1)

    if (config.spec.externAddr && isPublicAddress(advertisedAddr.host)) {
      const p2 = addressFactory.createSipURI(
        null,
        addrHost(config.spec.externAddr)
      )
      p2.setLrParam()
      p2.setPort(addrPort(config.spec.externAddr, localAddr))
      const pa2 = addressFactory.createAddress(p2)
      const rr2 = headerFactory.createRecordRouteHeader(pa2)
      requestOut.addFirst(rr2)
    }
  }
  return requestOut
}
const configureRequestURI = (request, routeInfo, route) => {
  const requestOut = request.clone()
  let uri

  if (
    routeInfo.getRoutingType() === RoutingType.DOMAIN_EGRESS_ROUTING ||
    routeInfo.getRoutingType() === RoutingType.PEER_EGRESS_ROUTING
  ) {
    uri = `sip:${getToUser(request)}@${route.gwHost}`
  } else if (isWebRTCClient(route)) {
    uri = `sip:${getUser(request)}@${route.received}:${route.rport}`
  } else {
    uri = route.contactURI
  }

  requestOut.setRequestURI(LocatorUtils.aorAsObj(uri))
  return requestOut
}
const configurePrivacy = (request, routeInfo) => {
  const requestOut = request.clone()
  requestOut.removeHeader('Privacy')
  const callee = routeInfo.getCallee()
  if (callee && equalsIgnoreCase(callee.kind, 'agent')) {
    let privacyHeader

    if (
      callee.spec.privacy &&
      equalsIgnoreCase(callee.spec.privacy, 'private')
    ) {
      const originFromHeader = requestOut.getHeader(FromHeader.NAME)
      const fromHeaderAddrs = addressFactory.createAddress(
        `"Anonymous" <sip:anonymous@anonymous.invalid>`
      )
      const fromHeader = headerFactory.createHeader(
        'From',
        fromHeaderAddrs.toString()
      )
      fromHeader.setTag(originFromHeader.getTag())
      requestOut.setHeader(fromHeader)
      privacyHeader = headerFactory.createHeader('Privacy', 'id')
    } else {
      privacyHeader = headerFactory.createHeader('Privacy', 'none')
    }

    requestOut.addHeader(privacyHeader)
  }
  return requestOut
}
const configureIdentity = (request, route) => {
  const requestOut = request.clone()
  if (route.thruGw) {
    const remotePartyIdHeader = headerFactory.createHeader(
      'Remote-Party-ID',
      `<sip:${route.number}@${route.gwHost}>;screen=yes;party=calling`
    )
    const dp = requestOut
      .getHeader(FromHeader.NAME)
      .getAddress()
      .getDisplayName()
    const displayName = dp ? `"${dp}" ` : ''
    const pAssertedIdentity = headerFactory.createHeader(
      'P-Asserted-Identity',
      `${displayName}<sip:${route.number}@${route.gwHost}>`
    )
    requestOut.setHeader(remotePartyIdHeader)
    requestOut.setHeader(pAssertedIdentity)
  }
  return requestOut
}
const configureXHeaders = (request, route) => {
  const requestOut = request.clone()
  if (route.thruGw) {
    const gwRefHeader = headerFactory.createHeader('X-Gateway-Ref', route.gwRef)
    requestOut.setHeader(gwRefHeader)
  }
  return requestOut
}
const isInDialog = request =>
  request.getHeader(ToHeader.NAME).getTag() !== null &&
  request.getHeader(FromHeader.NAME).getTag() !== null

module.exports.getAdvertisedAddr = getAdvertisedAddr
module.exports.configureRoute = configureRoute
module.exports.configureVia = configureVia
module.exports.configureProxyAuthorization = configureProxyAuthorization
module.exports.configureRequestURI = configureRequestURI
module.exports.configureMaxForwards = configureMaxForwards
module.exports.configureContact = configureContact
module.exports.configurePrivacy = configurePrivacy
module.exports.configureRecordRoute = configureRecordRoute
module.exports.configureIdentity = configureIdentity
module.exports.configureXHeaders = configureXHeaders
module.exports.configureCSeq = configureCSeq
module.exports.isInDialog = isInDialog
<|endoftext|>


<commit_before>import Ember from 'ember';
import FormElement from 'ember-bootstrap/components/bs-form-element';

const { computed } = Ember;

/**
 Render a form with the appropriate Bootstrap layout class (see `formLayout`).
 Allows setting a `model` that nested `Components.FormElement`s can access, and that can provide form validation through
 [ember-validations](https://github.com/dockyard/ember-validations)

 You can use whatever markup you like within the form:

 ```hbs
 {{#bs-form action="submit"}}
 {{#bs-form-group validation=firstNameValidation}}
 <label class="control-label">First name</label>
 {{bs-input type="text" value=firstname}}
 {{/bs-form-group}}
 {{/bs-form}}
 ```

 However to benefit from features such as automatic form markup, validations and validation markup, use `Components.FormElement`
 as nested components. See below for an example.

 ### Submitting the form

 When the form is submitted (e.g. by clicking a submit button), the event will be intercepted and the default action
 will be sent to the controller.
 When an [ember-validations](https://github.com/dockyard/ember-validations) validated model is supplied, validations
 rules are evaluated before, and if those fail, the "invalid" action is sent instead of the default "action".

 ### Use with Components.FormElement

 When using `Components.FormElement`s with their `property` set to property names of the form's validation enabled
 `model`, you gain some additional powerful features:
 * the appropriate Bootstrap markup for the given `formLayout` and the form element's `controlType` is automatically generated
 * markup for validation states and error messages is generated based on the model's validation, when submitting the form
 with an invalid validation, or when focusing out of invalid inputs

 ```hbs
 {{#bs-form formLayout="horizontal" model=this action="submit"}}
 {{bs-form-element controlType="email" label="Email" placeholder="Email" property="email"}}
 {{bs-form-element controlType="password" label="Password" placeholder="Password" property="password"}}
 {{bs-form-element controlType="checkbox" label="Remember me" property="rememberMe"}}
 {{bs-button defaultText="Submit" type="primary" buttonType="submit"}}
 {{/bs-form}}
 ```

 See the `Components.FormElement` API docs for further information.

 @class Form
 @namespace Components
 @extends Ember.Component
 @public
 */
export default Ember.Component.extend({
  tagName: 'form',
  classNameBindings: ['layoutClass'],
  ariaRole: 'form',

  /**
   * Bootstrap form class name (computed)
   *
   * @property layoutClass
   * @type string
   * @readonly
   * @protected
   *
   */
  layoutClass: computed('formLayout', function() {
    let layout = this.get('formLayout');
    return layout === 'vertical' ? 'form' : `form-${layout}`;
  }),

  /**
   * Set a model that this form should represent. This serves several purposes:
   *
   * * child `Components.FormElement`s can access and bind to this model by their `property`
   * * when the model supports validation by using the [ember-validations](https://github.com/dockyard/ember-validations) mixin,
   * child `Components.FormElement`s will look at the validation information of their `property` and render their form group accordingly.
   * Moreover the form's `submit` event handler will validate the model and deny submitting if the model is not validated successfully.
   *
   * @property model
   * @type Ember.Object
   * @public
   */
  model: null,

  /**
   * Set the layout of the form to either "vertical", "horizontal" or "inline". See http://getbootstrap.com/css/#forms-inline and http://getbootstrap.com/css/#forms-horizontal
   *
   * @property formLayout
   * @type string
   * @public
   */
  formLayout: 'vertical',

  /**
   * Check if the `model` has a validate method, i.e. supports validation by using [ember-validations](https://github.com/dockyard/ember-validations)
   *
   * @property hasValidator
   * @type boolean
   * @readonly
   * @protected
   */
  hasValidator: computed.notEmpty('model.validate'),

  /**
   * The Bootstrap grid class for form labels. This is used by the `Components.FormElement` class as a default for the
   * whole form.
   *
   * @property horizontalLabelGridClass
   * @type string
   * @default 'col-md-4'
   * @public
   */
  horizontalLabelGridClass: 'col-md-4',

  /**
   * If set to true pressing enter will submit the form, even if no submit button is present
   *
   * @property submitOnEnter
   * @type boolean
   * @default false
   * @public
   */
  submitOnEnter: false,

  /**
   * An array of `Components.FormElement`s that are children of this form.
   *
   * @property childFormElements
   * @type Array
   * @readonly
   * @protected
   */
  childFormElements: computed.filter('childViews', function(view) {
    return view instanceof FormElement;
  }),

  /**
   * Validate hook that will return a promise that will either resolve if the model is valid
   * or reject if it's not.
   *
   * @param Object model
   * @return Promise
   * @public
   */
  validate(/* model */) {
    Ember.deprecate('[ember-bootstrap] Validation support has been moved to 3rd party addons.\n' +
                    'ember-validations: https://github.com/kaliber5/ember-bootstrap-validations\n' +
                    'ember-cp-validations: https://github.com/offirgolan/ember-bootstrap-cp-validations\n', false);
  },

  /**
   * Submit handler that will send the default action ("action") to the controller when submitting the form.
   *
   * If there is a supplied `model` that supports validation (`hasValidator`) the model will be validated before, and
   * only if validation is successful the default action will be sent. Otherwise an "invalid" action will be sent, and
   * all the `showValidation` property of all child `Components.FormElement`s will be set to true, so error state and
   * messages will be shown automatically.
   *
   * @event submit
   * @private
   */
  submit(e) {
    if (e) {
      e.preventDefault();
    }

    if (!this.get('hasValidator')) {
      return this.sendAction();
    } else {
      let validationPromise = this.validate(this.get('model'));
      if (validationPromise && validationPromise instanceof Ember.RSVP.Promise) {
        validationPromise.then(() => this.sendAction(), () => {
          this.get('childFormElements').setEach('showValidation', true);
          return this.sendAction('invalid');
        });
      }
    }
  },

  keyPress(e) {
    let code = e.keyCode || e.which;
    if (code === 13 && this.get('submitOnEnter')) {
      this.$().submit();
    }
  }
});
<commit_msg>Removed ember-validations left over<commit_after>import Ember from 'ember';
import FormElement from 'ember-bootstrap/components/bs-form-element';

const { computed } = Ember;

/**
 Render a form with the appropriate Bootstrap layout class (see `formLayout`).
 Allows setting a `model` that nested `Components.FormElement`s can access, and that can provide form validation through
 [ember-validations](https://github.com/dockyard/ember-validations)

 You can use whatever markup you like within the form:

 ```hbs
 {{#bs-form action="submit"}}
 {{#bs-form-group validation=firstNameValidation}}
 <label class="control-label">First name</label>
 {{bs-input type="text" value=firstname}}
 {{/bs-form-group}}
 {{/bs-form}}
 ```

 However to benefit from features such as automatic form markup, validations and validation markup, use `Components.FormElement`
 as nested components. See below for an example.

 ### Submitting the form

 When the form is submitted (e.g. by clicking a submit button), the event will be intercepted and the default action
 will be sent to the controller.
 When an [ember-validations](https://github.com/dockyard/ember-validations) validated model is supplied, validations
 rules are evaluated before, and if those fail, the "invalid" action is sent instead of the default "action".

 ### Use with Components.FormElement

 When using `Components.FormElement`s with their `property` set to property names of the form's validation enabled
 `model`, you gain some additional powerful features:
 * the appropriate Bootstrap markup for the given `formLayout` and the form element's `controlType` is automatically generated
 * markup for validation states and error messages is generated based on the model's validation, when submitting the form
 with an invalid validation, or when focusing out of invalid inputs

 ```hbs
 {{#bs-form formLayout="horizontal" model=this action="submit"}}
 {{bs-form-element controlType="email" label="Email" placeholder="Email" property="email"}}
 {{bs-form-element controlType="password" label="Password" placeholder="Password" property="password"}}
 {{bs-form-element controlType="checkbox" label="Remember me" property="rememberMe"}}
 {{bs-button defaultText="Submit" type="primary" buttonType="submit"}}
 {{/bs-form}}
 ```

 See the `Components.FormElement` API docs for further information.

 @class Form
 @namespace Components
 @extends Ember.Component
 @public
 */
export default Ember.Component.extend({
  tagName: 'form',
  classNameBindings: ['layoutClass'],
  ariaRole: 'form',

  /**
   * Bootstrap form class name (computed)
   *
   * @property layoutClass
   * @type string
   * @readonly
   * @protected
   *
   */
  layoutClass: computed('formLayout', function() {
    let layout = this.get('formLayout');
    return layout === 'vertical' ? 'form' : `form-${layout}`;
  }),

  /**
   * Set a model that this form should represent. This serves several purposes:
   *
   * * child `Components.FormElement`s can access and bind to this model by their `property`
   * * when the model supports validation by using the [ember-validations](https://github.com/dockyard/ember-validations) mixin,
   * child `Components.FormElement`s will look at the validation information of their `property` and render their form group accordingly.
   * Moreover the form's `submit` event handler will validate the model and deny submitting if the model is not validated successfully.
   *
   * @property model
   * @type Ember.Object
   * @public
   */
  model: null,

  /**
   * Set the layout of the form to either "vertical", "horizontal" or "inline". See http://getbootstrap.com/css/#forms-inline and http://getbootstrap.com/css/#forms-horizontal
   *
   * @property formLayout
   * @type string
   * @public
   */
  formLayout: 'vertical',

  /**
   * Check if validating the model is supported. This needs to be implemented by another addon.
   *
   * @property hasValidator
   * @type boolean
   * @readonly
   * @protected
   */
  hasValidator: false,

  /**
   * The Bootstrap grid class for form labels. This is used by the `Components.FormElement` class as a default for the
   * whole form.
   *
   * @property horizontalLabelGridClass
   * @type string
   * @default 'col-md-4'
   * @public
   */
  horizontalLabelGridClass: 'col-md-4',

  /**
   * If set to true pressing enter will submit the form, even if no submit button is present
   *
   * @property submitOnEnter
   * @type boolean
   * @default false
   * @public
   */
  submitOnEnter: false,

  /**
   * An array of `Components.FormElement`s that are children of this form.
   *
   * @property childFormElements
   * @type Array
   * @readonly
   * @protected
   */
  childFormElements: computed.filter('childViews', function(view) {
    return view instanceof FormElement;
  }),

  /**
   * Validate hook that will return a promise that will either resolve if the model is valid
   * or reject if it's not.
   *
   * @param Object model
   * @return Promise
   * @public
   */
  validate(/* model */) {
    Ember.deprecate('[ember-bootstrap] Validation support has been moved to 3rd party addons.\n' +
                    'ember-validations: https://github.com/kaliber5/ember-bootstrap-validations\n' +
                    'ember-cp-validations: https://github.com/offirgolan/ember-bootstrap-cp-validations\n', false);
  },

  /**
   * Submit handler that will send the default action ("action") to the controller when submitting the form.
   *
   * If there is a supplied `model` that supports validation (`hasValidator`) the model will be validated before, and
   * only if validation is successful the default action will be sent. Otherwise an "invalid" action will be sent, and
   * all the `showValidation` property of all child `Components.FormElement`s will be set to true, so error state and
   * messages will be shown automatically.
   *
   * @event submit
   * @private
   */
  submit(e) {
    if (e) {
      e.preventDefault();
    }

    if (!this.get('hasValidator')) {
      return this.sendAction();
    } else {
      let validationPromise = this.validate(this.get('model'));
      if (validationPromise && validationPromise instanceof Ember.RSVP.Promise) {
        validationPromise.then(() => this.sendAction(), () => {
          this.get('childFormElements').setEach('showValidation', true);
          return this.sendAction('invalid');
        });
      }
    }
  },

  keyPress(e) {
    let code = e.keyCode || e.which;
    if (code === 13 && this.get('submitOnEnter')) {
      this.$().submit();
    }
  }
});
<|endoftext|>


<commit_before>/* globals require, module */
/**
 * @module app/Kernel
 * @param {object} context
 * @property {string} context.functionName
 * @property {function} context.succeed
 * @property {function} context.fail
 * @param {object} event
 * @property {string} event.getdata
 * @property {string} event.postdata
 * @class
 */
function Kernel(context, event) {
    /** @constant {number} */
    this.kernelVersion = 1;
    this.context       = context;
    this.event         = event;

    this.mapValues     = {
        "%kernel%": this,
        "%context%": context,
        "%event%": event
    };

    //Since the Kernel Masquerades as context, we need to copy just it's variables to it, functions have been mapped to the context object.
    for (var attr in JSON.parse(JSON.stringify(context))) {
        if (context.hasOwnProperty(attr)) {
            this[attr] = context[attr];
        }
    }

    var qs            = require('qs');
    this.request      = {
        "get" : "",
        "post": "",
        "all" : function() {
            var data   = [
                (this.get) ? JSON.stringify(this.get)
                                 .trim() : '',
                (this.post) ? JSON.stringify(this.post)
                                  .trim() : ''
            ];
            var result = data.filter(Boolean)
                             .join('|')
                             .replace("}|{", ",");
            return (result) ? JSON.parse(result) : false;
        }
    };

    this.request.get  = (typeof event.getdata  !== 'undefined' && event.getdata.trim()  !== '') ? qs.parse(event.getdata)  : false;
    this.request.post = (typeof event.postdata !== 'undefined' && event.postdata.trim() !== '') ? qs.parse(event.postdata) : false;

    var winston       = require('winston');
    this.logger       = new (winston.Logger)({
        transports: [
            new (winston.transports.Console)({
                timestamp: function() {
                    return Date.now();
                },
                formatter: function(options) {
                    return '[' + options.level.toUpperCase() + '] ' + (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t' + JSON.stringify(options.meta) : '' );
                }
            })
        ]
    });

    this.logger.setLevels(winston.config.syslog.levels);

    /*
     We try to grab the environment from event stage then from the function name, if those faile we set to DEFAULT.
     */
    var nameArray     = (0 <= context.functionName.indexOf('-')) ? context.functionName.split('-') : [
        context.functionName, 'DEFAULT'
    ];
    var environment   = (typeof event.stage !== 'undefined') ? event.stage : nameArray[1];
    this.functionName = nameArray[0];
    this.loadEnvironment(environment);
    this.loadServices();
}

Kernel.prototype.returnResult = 'SUCCESS';

/**
 * @function loadEnvironment
 * Set the environment and load the config based on the environment
 * @param {string} environment
 */
Kernel.prototype.loadEnvironment = function loadEnvironment(environment) {
    this.environment = environment.toUpperCase();
    var path         = String('../etc/' + this.environment)
        .replace('/DEFAULT', '');
    this.config      = require(path);
    if ('DEFAULT' == environment && 'undefined' !== typeof this.config.environment && 'DEFAULT' !== this.config.environment) {
        this.loadEnvironment(this.config.environment);
    } else {
        this.config.succeedFails = (typeof this.config.succeedFails !== 'undefined') ? this.config.succeedFails : false;
        var logLevel             = this.config.logLevel || 'error';
        this.setLogLevel(logLevel);
        this.log('Set environment to: ' + this.environment);
    }
};

Kernel.prototype.loadServices = function loadServices() {
    this.services = require('../etc/services');
};

Kernel.prototype.getService = function getService(serviceName) {
    var path = ('undefined' !== typeof this.services[serviceName]) ? '..' + this.services[serviceName].path : serviceName;
    var service = require(path);
    var arguments = this.services[serviceName].arguments || [];
    var commands  = this.services[serviceName].commands || [];
    var instance = Object.create(service.prototype);

    var argumentFilter = function(array, that) {
        return array.map(function(value) {
            return (typeof this.mapValues[value] !== "undefined") ? this.mapValues[value] : value;
        }, that);
    };

    if (arguments.length > 0) {
        service.apply(instance, argumentFilter(arguments, this))
    } else {
        instance = new service;
    }

    if(commands.length > 0) {
        commands.map(function(value){
            switch(typeof value) {
                case "object":
                    var func = instance[value["name"]];
                    if (value["arguments"].length > 0) {
                        func.apply(instance, argumentFilter(value["arguments"], this));
                    } else {
                        instance[value["name"]]();
                    }
                    break;
                case "string":
                    instance[value]();
                    break;
                case "default":
                    this.log("Unknown Command Definition: Expecting String(\"Function Name\") or Object({\"name\":\"Function Name\", \"arguments\":[<<Function Arguments>>]}).", "alert");
            }
        }, this);
    }

    return instance;
};

/**
 * Set the log level
 * @param {string} level
 */
Kernel.prototype.setLogLevel = function setLogLevel(level) {
    level = level.toLowerCase();
    if (typeof this.logger.levels[level] == "undefined") {
        this.logger.error("No such Log Level: " + level);
    } else {
        this.config.logLevel = level;
        this.logger.level    = this.config.logLevel;
    }
};

/**
 * @param {string} message
 * @param {string} [level]
 */
Kernel.prototype.log = function log(message, level) {
    level = level || 'info';
    level = level.toLowerCase();
    if (typeof this.logger.levels[level] == "undefined") {
        message = "No such Log Level: " + level;
        level   = 'error';
    }

    if (typeof message === 'object') {
        message = JSON.stringify(message);
    }
    this.logger.log(level, message);
};

/**
 * Overrides existing setting. Tells error handler whether or not to context.succeed failures.
 * @param {boolean} succeedFails
 */
Kernel.prototype.setSucceedFails = function setSucceedFails(succeedFails) {
    this.config.succeedFails = succeedFails;
};

/**
 *
 * @param {(string|object)} [err]
 * @param {(string|object)} [result]
 */
Kernel.prototype.done = function done(err, result) {
    var isSuccess     = true;
    var logLevel      = 'debug';
    this.returnResult = result || this.returnResult;

    if (err) {
        if (typeof err === 'object') {
            err = err.stack + JSON.stringify(err);
        }
        this.returnResult = err;
        logLevel          = 'crit';
        isSuccess         = false;
    }

    this.log(this.returnResult, logLevel);
    //context.fail forces lambda to try 2 or 3 more times.
    //if succeedFails is true, we go ahead and succeed and handle the failure elsewhere.
    if (this.config.succeedFails || isSuccess) {
        this.context.succeed(this.returnResult);
    } else {
        this.context.fail(this.returnResult);
    }
};

/**
 *
 * @param {(string|object)} [result]
 */
Kernel.prototype.succeed = function succeed(result) {
    this.done(false, result);
};

/**
 *
 * @param {(string|object)} [err]
 */
Kernel.prototype.fail = function fail(err) {
    this.done(err);
};

Kernel.prototype.getRemainingTimeInMillis = function getRemainingTimeInMillis() {
    return this.context.getRemainingTimeInMillis();
};

Kernel.prototype.getRemainingTimeInSecs = function getRemainingTimeInSecs() {
    return Math.floor(this.context.getRemainingTimeInMillis() / 1000);
};

Kernel.prototype.constructor = Kernel;
module.exports = Kernel;<commit_msg>Error Handling for missing config file.<commit_after>/* globals require, module */
/**
 * @module app/Kernel
 * @param {object} context
 * @property {string} context.functionName
 * @property {function} context.succeed
 * @property {function} context.fail
 * @param {object} event
 * @property {string} event.getdata
 * @property {string} event.postdata
 * @class
 */
function Kernel(context, event) {
    /** @constant {number} */
    this.kernelVersion = 1;
    this.context       = context;
    this.event         = event;

    this.mapValues     = {
        "%kernel%": this,
        "%context%": context,
        "%event%": event
    };

    //Since the Kernel Masquerades as context, we need to copy just it's variables to it, functions have been mapped to the context object.
    for (var attr in JSON.parse(JSON.stringify(context))) {
        if (context.hasOwnProperty(attr)) {
            this[attr] = context[attr];
        }
    }

    var qs            = require('qs');
    this.request      = {
        "get" : "",
        "post": "",
        "all" : function() {
            var data   = [
                (this.get) ? JSON.stringify(this.get)
                                 .trim() : '',
                (this.post) ? JSON.stringify(this.post)
                                  .trim() : ''
            ];
            var result = data.filter(Boolean)
                             .join('|')
                             .replace("}|{", ",");
            return (result) ? JSON.parse(result) : false;
        }
    };

    this.request.get  = (typeof event.getdata  !== 'undefined' && event.getdata.trim()  !== '') ? qs.parse(event.getdata)  : false;
    this.request.post = (typeof event.postdata !== 'undefined' && event.postdata.trim() !== '') ? qs.parse(event.postdata) : false;

    var winston       = require('winston');
    this.logger       = new (winston.Logger)({
        transports: [
            new (winston.transports.Console)({
                timestamp: function() {
                    return Date.now();
                },
                formatter: function(options) {
                    return '[' + options.level.toUpperCase() + '] ' + (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t' + JSON.stringify(options.meta) : '' );
                }
            })
        ]
    });

    this.logger.setLevels(winston.config.syslog.levels);

    /*
     We try to grab the environment from event stage then from the function name, if those fail we set to DEFAULT.
     */
    var nameArray     = (0 <= context.functionName.indexOf('-')) ? context.functionName.split('-') : [
        context.functionName, 'DEFAULT'
    ];
    var environment   = (typeof event.stage !== 'undefined') ? event.stage : nameArray[1];
    this.functionName = nameArray[0];
    this.loadEnvironment(environment);
    this.loadServices();
}

Kernel.prototype.returnResult = 'SUCCESS';

/**
 * @function loadEnvironment
 * Set the environment and load the config based on the environment
 * @param {string} environment
 */
Kernel.prototype.loadEnvironment = function loadEnvironment(environment) {
    this.environment = environment.toUpperCase();
    var path         = String('../etc/' + this.environment).replace('/DEFAULT', '');
    try {
        this.config = require(path);
    } catch (err) {
        this.config = {};
        this.log(String(err).replace('Error: ', '') + " Code: " + err.code, ('DEFAULT' == environment) ? 'warning' : 'error');
    }
    if ('DEFAULT' == environment && 'undefined' !== typeof this.config.environment && 'DEFAULT' !== this.config.environment) {
        this.loadEnvironment(this.config.environment);
    } else {
        this.config.succeedFails = (typeof this.config.succeedFails !== 'undefined') ? this.config.succeedFails : false;
        var logLevel             = this.config.logLevel || 'error';
        this.setLogLevel(logLevel);
        this.log('Set environment to: ' + this.environment);
    }
};

Kernel.prototype.loadServices = function loadServices() {
    this.services = require('../etc/services');
};

Kernel.prototype.getService = function getService(serviceName) {
    var path = ('undefined' !== typeof this.services[serviceName]) ? '..' + this.services[serviceName].path : serviceName;
    var service = require(path);
    var arguments = this.services[serviceName].arguments || [];
    var commands  = this.services[serviceName].commands || [];
    var instance = Object.create(service.prototype);

    var argumentFilter = function(array, that) {
        return array.map(function(value) {
            return (typeof this.mapValues[value] !== "undefined") ? this.mapValues[value] : value;
        }, that);
    };

    if (arguments.length > 0) {
        service.apply(instance, argumentFilter(arguments, this))
    } else {
        instance = new service;
    }

    if(commands.length > 0) {
        commands.map(function(value){
            switch(typeof value) {
                case "object":
                    var func = instance[value["name"]];
                    if (value["arguments"].length > 0) {
                        func.apply(instance, argumentFilter(value["arguments"], this));
                    } else {
                        instance[value["name"]]();
                    }
                    break;
                case "string":
                    instance[value]();
                    break;
                case "default":
                    this.log("Unknown Command Definition: Expecting String(\"Function Name\") or Object({\"name\":\"Function Name\", \"arguments\":[<<Function Arguments>>]}).", "alert");
            }
        }, this);
    }

    return instance;
};

/**
 * Set the log level
 * @param {string} level
 */
Kernel.prototype.setLogLevel = function setLogLevel(level) {
    level = level.toLowerCase();
    if (typeof this.logger.levels[level] == "undefined") {
        this.logger.error("No such Log Level: " + level);
    } else {
        this.config.logLevel = level;
        this.logger.level    = this.config.logLevel;
    }
};

/**
 * @param {string} message
 * @param {string} [level]
 */
Kernel.prototype.log = function log(message, level) {
    level = level || 'info';
    level = level.toLowerCase();
    if (typeof this.logger.levels[level] == "undefined") {
        message = "No such Log Level: " + level;
        level   = 'error';
    }

    if (typeof message === 'object') {
        message = JSON.stringify(message);
    }
    this.logger.log(level, message);
};

/**
 * Overrides existing setting. Tells error handler whether or not to context.succeed failures.
 * @param {boolean} succeedFails
 */
Kernel.prototype.setSucceedFails = function setSucceedFails(succeedFails) {
    this.config.succeedFails = succeedFails;
};

/**
 *
 * @param {(string|object)} [err]
 * @param {(string|object)} [result]
 */
Kernel.prototype.done = function done(err, result) {
    var isSuccess     = true;
    var logLevel      = 'debug';
    this.returnResult = result || this.returnResult;

    if (err) {
        if (typeof err === 'object') {
            err = err.stack + JSON.stringify(err);
        }
        this.returnResult = err;
        logLevel          = 'crit';
        isSuccess         = false;
    }

    this.log(this.returnResult, logLevel);
    //context.fail forces lambda to try 2 or 3 more times.
    //if succeedFails is true, we go ahead and succeed and handle the failure elsewhere.
    if (this.config.succeedFails || isSuccess) {
        this.context.succeed(this.returnResult);
    } else {
        this.context.fail(this.returnResult);
    }
};

/**
 *
 * @param {(string|object)} [result]
 */
Kernel.prototype.succeed = function succeed(result) {
    this.done(false, result);
};

/**
 *
 * @param {(string|object)} [err]
 */
Kernel.prototype.fail = function fail(err) {
    this.done(err);
};

Kernel.prototype.getRemainingTimeInMillis = function getRemainingTimeInMillis() {
    return this.context.getRemainingTimeInMillis();
};

Kernel.prototype.getRemainingTimeInSecs = function getRemainingTimeInSecs() {
    return Math.floor(this.context.getRemainingTimeInMillis() / 1000);
};

Kernel.prototype.constructor = Kernel;
module.exports = Kernel;<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Daniel Cohen Gindi (danielgindi@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* global DGTable, _ */
DGTable.ColumnCollection = (function () {
    'use strict';

    // Define class RowCollection
    var ColumnCollection = function() {

        // Instantiate an Array. Seems like the `.length = ` of an inherited Array does not work well.
        // I will not use the IFRAME solution either in fear of memory leaks, and we're supporting large datasets...
        var collection = [];

        // Synthetically set the 'prototype'
        _.extend(collection, ColumnCollection.prototype);

        // Call initializer
        collection.initialize.apply(collection, arguments);

        return collection;
    };

    // Inherit Array
    ColumnCollection.prototype = [];

    ColumnCollection.prototype.initialize = function() {

    };

    /**
     * Get the column by this name
     * @param {String} column column name
     * @returns {Object} the column object
     */
    ColumnCollection.prototype.get = function(column) {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i].name == column) {
                return this[i];
            }
        }
        return null;
    };

    /**
     * Get the index of the column by this name
     * @param {String} column column name
     * @returns {int} the index of this column
     */
    ColumnCollection.prototype.indexOf = function(column) {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i].name == column) {
                return i;
            }
        }
        return -1;
    };

    /**
     * Get the column by the specified order
     * @param {Number} order the column's order
     * @returns {Object} the column object
     */
    ColumnCollection.prototype.getByOrder = function(order) {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i].order == order) {
                return this[i];
            }
        }
        return null;
    };

    /**
     * Normalize order
     * @returns {ColumnCollection} self
     */
    ColumnCollection.prototype.normalizeOrder = function() {
        var ordered = [], i;
        for (i = 0; i < this.length; i++) {
            ordered.push(this[i]);
        }
        ordered.sort(function(col1, col2){ return col1.order < col2.order ? -1 : (col1.order > col2.order ? 1 : 0); });
        for (i = 0; i < ordered.length; i++) {
            ordered[i].order = i;
        }
        return this;
    };

    /**
     * Get the array of visible columns, order by the order property
     * @returns {Array<Object>} ordered array of visible columns
     */
    ColumnCollection.prototype.getVisibleColumns = function() {
        var visible = [];
        for (var i = 0, column; i < this.length; i++) {
            column = this[i];
            if (column.visible) {
                visible.push(column);
            }
        }
        visible.sort(function(col1, col2){ return col1.order < col2.order ? -1 : (col1.order > col2.order ? 1 : 0); });
        return visible;
    };

    /**
     * @returns {int} maximum order currently in the array
     */
    ColumnCollection.prototype.getMaxOrder = function() {
        var order = 0;
        for (var i = 0, column; i < this.length; i++) {
            column = this[i];
            if (column.order > order) {
                order = column.order;
            }
        }
        return order;
    };

    /**
     * Move a column to a new spot in the collection
     * @param {Object} src the column to move
     * @param {Object} dest the destination column
     * @returns {ColumnCollection} self
     */
    ColumnCollection.prototype.moveColumn = function (src, dest) {
        if (src && dest) {
            var srcOrder = src.order, destOrder = dest.order, i, col;
            if (srcOrder < destOrder) {
                for (i = srcOrder + 1; i <= destOrder; i++) {
                    col = this.getByOrder(i);
                    col.order--;
                }
            } else {
                for (i = srcOrder - 1; i >= destOrder; i--) {
                    col = this.getByOrder(i);
                    col.order++;
                }
            }
            src.order = destOrder;
        }
        return this;
    };

    return ColumnCollection;

})();<commit_msg>Make sure we always have at least one column visible<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Daniel Cohen Gindi (danielgindi@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* global DGTable, _ */
DGTable.ColumnCollection = (function () {
    'use strict';

    // Define class RowCollection
    var ColumnCollection = function() {

        // Instantiate an Array. Seems like the `.length = ` of an inherited Array does not work well.
        // I will not use the IFRAME solution either in fear of memory leaks, and we're supporting large datasets...
        var collection = [];

        // Synthetically set the 'prototype'
        _.extend(collection, ColumnCollection.prototype);

        // Call initializer
        collection.initialize.apply(collection, arguments);

        return collection;
    };

    // Inherit Array
    ColumnCollection.prototype = [];

    ColumnCollection.prototype.initialize = function() {

    };

    /**
     * Get the column by this name
     * @param {String} column column name
     * @returns {Object} the column object
     */
    ColumnCollection.prototype.get = function(column) {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i].name == column) {
                return this[i];
            }
        }
        return null;
    };

    /**
     * Get the index of the column by this name
     * @param {String} column column name
     * @returns {int} the index of this column
     */
    ColumnCollection.prototype.indexOf = function(column) {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i].name == column) {
                return i;
            }
        }
        return -1;
    };

    /**
     * Get the column by the specified order
     * @param {Number} order the column's order
     * @returns {Object} the column object
     */
    ColumnCollection.prototype.getByOrder = function(order) {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i].order == order) {
                return this[i];
            }
        }
        return null;
    };

    /**
     * Normalize order
     * @returns {ColumnCollection} self
     */
    ColumnCollection.prototype.normalizeOrder = function() {
        var ordered = [], i;
        for (i = 0; i < this.length; i++) {
            ordered.push(this[i]);
        }
        ordered.sort(function(col1, col2){ return col1.order < col2.order ? -1 : (col1.order > col2.order ? 1 : 0); });
        for (i = 0; i < ordered.length; i++) {
            ordered[i].order = i;
        }
        return this;
    };

    /**
     * Get the array of visible columns, order by the order property
     * @returns {Array<Object>} ordered array of visible columns
     */
    ColumnCollection.prototype.getVisibleColumns = function() {
        var visible = [];
        for (var i = 0, column; i < this.length; i++) {
            column = this[i];
            if (column.visible) {
                visible.push(column);
            }
        }
        if (visible.length === 0 && this.length) {
            visible.push(this[0]);
        }
        visible.sort(function(col1, col2){ return col1.order < col2.order ? -1 : (col1.order > col2.order ? 1 : 0); });
        return visible;
    };

    /**
     * @returns {int} maximum order currently in the array
     */
    ColumnCollection.prototype.getMaxOrder = function() {
        var order = 0;
        for (var i = 0, column; i < this.length; i++) {
            column = this[i];
            if (column.order > order) {
                order = column.order;
            }
        }
        return order;
    };

    /**
     * Move a column to a new spot in the collection
     * @param {Object} src the column to move
     * @param {Object} dest the destination column
     * @returns {ColumnCollection} self
     */
    ColumnCollection.prototype.moveColumn = function (src, dest) {
        if (src && dest) {
            var srcOrder = src.order, destOrder = dest.order, i, col;
            if (srcOrder < destOrder) {
                for (i = srcOrder + 1; i <= destOrder; i++) {
                    col = this.getByOrder(i);
                    col.order--;
                }
            } else {
                for (i = srcOrder - 1; i >= destOrder; i--) {
                    col = this.getByOrder(i);
                    col.order++;
                }
            }
            src.order = destOrder;
        }
        return this;
    };

    return ColumnCollection;

})();<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// WARNING! This list should be in sync with the equivalent enum
// located at tizen.h. Remember to update tizen.h if you change
// something here.
var errors = {
  '-1': { type: 'NO_ERROR', name: 'NoError', message: '' },

  '0': { type: 'UNKNOWN_ERR', name: 'UnknownError', message: '' },
  '1': { type: 'INDEX_SIZE_ERR', name: 'IndexSizeError', message: '' },
  '2': { type: 'DOMSTRING_SIZE_ERR', name: 'DOMStringSizeError', message: '' },
  '3': { type: 'HIERARCHY_REQUEST_ERR', name: 'HierarchyRequestError', message: '' },
  '4': { type: 'WRONG_DOCUMENT_ERR', name: 'WrongDocumentError', message: '' },
  '5': { type: 'INVALID_CHARACTER_ERR', name: 'InvalidCharacterError', message: '' },
  '6': { type: 'NO_DATA_ALLOWED_ERR', name: 'NoDataAllowedError', message: '' },
  '7': { type: 'NO_MODIFICATION_ALLOWED_ERR', name: 'NoModificationAllowedError', message: '' },
  '8': { type: 'NOT_FOUND_ERR', name: 'NotFoundError', message: '' },
  '9': { type: 'NOT_SUPPORTED_ERR', name: 'Not_supportedError', message: '' },
  '10': { type: 'INUSE_ATTRIBUTE_ERR', name: 'InuseAttributeError', message: '' },
  '11': { type: 'INVALID_STATE_ERR', name: 'InvalidStateError', message: '' },
  '12': { type: 'SYNTAX_ERR', name: 'SyntaxError', message: '' },
  '13': { type: 'INVALID_MODIFICATION_ERR', name: 'InvalidModificationError', message: '' },
  '14': { type: 'NAMESPACE_ERR', name: 'NamespaceError', message: '' },
  '15': { type: 'INVALID_ACCESS_ERR', name: 'InvalidAccessError', message: '' },
  '16': { type: 'VALIDATION_ERR', name: 'ValidationError', message: '' },
  '17': { type: 'TYPE_MISMATCH_ERR', name: 'TypeMismatchError', message: '' },
  '18': { type: 'SECURITY_ERR', name: 'SecurityError', message: '' },
  '19': { type: 'NETWORK_ERR', name: 'NetworkError', message: '' },
  '20': { type: 'ABORT_ERR', name: 'AbortError', message: '' },
  '21': { type: 'URL_MISMATCH_ERR', name: 'UrlMismatchError', message: '' },
  '22': { type: 'QUOTA_EXCEEDED_ERR', name: 'QuotaExceededError', message: '' },
  '23': { type: 'TIMEOUT_ERR', name: 'TimeoutError', message: '' },
  '24': { type: 'INVALID_NODE_TYPE_ERR', name: 'InvalidNodeTypeError', message: '' },
  '25': { type: 'DATA_CLONE_ERR', name: 'DataCloneError', message: '' },

  // Error codes for these errors are not really defined anywhere.
  '100': { type: 'INVALID_VALUES_ERR', name: 'InvalidValuesError', message: '' },
  '101': { type: 'IO_ERR', name: 'IOError', message: '' },
  '102': { type: 'PERMISSION_DENIED_ERR', name: 'Permission_deniedError', message: '' },
  '103': { type: 'SERVICE_NOT_AVAILABLE_ERR', name: 'ServiceNotAvailableError', message: '' }
};

exports.WebAPIException = function(code, message, name) {
  var _code, _message, _name;

  if (typeof code !== 'number') {
    _code = 0;
    _message = errors[0].message;
    _name = errors[0].name;
  } else {
    _code = code;
    if (typeof message === 'string') {
      _message = message;
    } else {
      _message = errors[_code].message;
    } if (typeof name === 'string') {
      _name = name;
    } else {
      _name = errors[_code].name;
    }
  }

  this.__defineGetter__('code', function() { return _code; });
  this.__defineGetter__('message', function() { return _message; });
  this.__defineGetter__('name', function() { return _name; });
};

for (var value in errors)
  Object.defineProperty(tizen.WebAPIException, errors[value].type, { value: parseInt(value) });

exports.WebAPIError = function(code, message, name) {
  var _code, _message, _name;

  if (typeof code !== 'number') {
    _code = errors[0].value;
    _message = errors[0].message;
    _name = errors[0].name;
  } else {
    _code = code;
    if (typeof message === 'string') {
      _message = message;
    } else {
      _message = errors[_code].message;
    } if (typeof name === 'string') {
      _name = name;
    } else {
      _name = errors[_code].name;
    }
  }

  this.__defineGetter__('code', function() { return _code; });
  this.__defineGetter__('message', function() { return _message; });
  this.__defineGetter__('name', function() { return _name; });
};

for (var value in errors)
  Object.defineProperty(tizen.WebAPIError, errors[value].type, { value: value });

// NOTE: Stubs for Application. These are needed for running TCT until
// we have a proper Application API implementation.
exports.application = {
  getAppInfo: function() { return { id: 0 } }
};

exports.ApplicationControlData = function(key, value) {
  this.key = key;
  this.value = value;
};

exports.ApplicationControl = function(operation, uri, mime, category, data) {
  this.operation = operation;
  this.uri = uri;
  this.mime = mime;
  this.category = category;
  this.data = data || [];
};
<commit_msg>[Common] Fix IO_ERR message<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// WARNING! This list should be in sync with the equivalent enum
// located at tizen.h. Remember to update tizen.h if you change
// something here.
var errors = {
  '-1': { type: 'NO_ERROR', name: 'NoError', message: '' },

  '0': { type: 'UNKNOWN_ERR', name: 'UnknownError', message: '' },
  '1': { type: 'INDEX_SIZE_ERR', name: 'IndexSizeError', message: '' },
  '2': { type: 'DOMSTRING_SIZE_ERR', name: 'DOMStringSizeError', message: '' },
  '3': { type: 'HIERARCHY_REQUEST_ERR', name: 'HierarchyRequestError', message: '' },
  '4': { type: 'WRONG_DOCUMENT_ERR', name: 'WrongDocumentError', message: '' },
  '5': { type: 'INVALID_CHARACTER_ERR', name: 'InvalidCharacterError', message: '' },
  '6': { type: 'NO_DATA_ALLOWED_ERR', name: 'NoDataAllowedError', message: '' },
  '7': { type: 'NO_MODIFICATION_ALLOWED_ERR', name: 'NoModificationAllowedError', message: '' },
  '8': { type: 'NOT_FOUND_ERR', name: 'NotFoundError', message: '' },
  '9': { type: 'NOT_SUPPORTED_ERR', name: 'Not_supportedError', message: '' },
  '10': { type: 'INUSE_ATTRIBUTE_ERR', name: 'InuseAttributeError', message: '' },
  '11': { type: 'INVALID_STATE_ERR', name: 'InvalidStateError', message: '' },
  '12': { type: 'SYNTAX_ERR', name: 'SyntaxError', message: '' },
  '13': { type: 'INVALID_MODIFICATION_ERR', name: 'InvalidModificationError', message: '' },
  '14': { type: 'NAMESPACE_ERR', name: 'NamespaceError', message: '' },
  '15': { type: 'INVALID_ACCESS_ERR', name: 'InvalidAccessError', message: '' },
  '16': { type: 'VALIDATION_ERR', name: 'ValidationError', message: '' },
  '17': { type: 'TYPE_MISMATCH_ERR', name: 'TypeMismatchError', message: '' },
  '18': { type: 'SECURITY_ERR', name: 'SecurityError', message: '' },
  '19': { type: 'NETWORK_ERR', name: 'NetworkError', message: '' },
  '20': { type: 'ABORT_ERR', name: 'AbortError', message: '' },
  '21': { type: 'URL_MISMATCH_ERR', name: 'UrlMismatchError', message: '' },
  '22': { type: 'QUOTA_EXCEEDED_ERR', name: 'QuotaExceededError', message: '' },
  '23': { type: 'TIMEOUT_ERR', name: 'TimeoutError', message: '' },
  '24': { type: 'INVALID_NODE_TYPE_ERR', name: 'InvalidNodeTypeError', message: '' },
  '25': { type: 'DATA_CLONE_ERR', name: 'DataCloneError', message: '' },

  // Error codes for these errors are not really defined anywhere.
  '100': { type: 'INVALID_VALUES_ERR', name: 'InvalidValuesError', message: '' },
  '101': { type: 'IO_ERR', name: 'IOError', message: 'IOError' },
  '102': { type: 'PERMISSION_DENIED_ERR', name: 'Permission_deniedError', message: '' },
  '103': { type: 'SERVICE_NOT_AVAILABLE_ERR', name: 'ServiceNotAvailableError', message: '' }
};

exports.WebAPIException = function(code, message, name) {
  var _code, _message, _name;

  if (typeof code !== 'number') {
    _code = 0;
    _message = errors[0].message;
    _name = errors[0].name;
  } else {
    _code = code;
    if (typeof message === 'string') {
      _message = message;
    } else {
      _message = errors[_code].message;
    } if (typeof name === 'string') {
      _name = name;
    } else {
      _name = errors[_code].name;
    }
  }

  this.__defineGetter__('code', function() { return _code; });
  this.__defineGetter__('message', function() { return _message; });
  this.__defineGetter__('name', function() { return _name; });
};

for (var value in errors)
  Object.defineProperty(tizen.WebAPIException, errors[value].type, { value: parseInt(value) });

exports.WebAPIError = function(code, message, name) {
  var _code, _message, _name;

  if (typeof code !== 'number') {
    _code = errors[0].value;
    _message = errors[0].message;
    _name = errors[0].name;
  } else {
    _code = code;
    if (typeof message === 'string') {
      _message = message;
    } else {
      _message = errors[_code].message;
    } if (typeof name === 'string') {
      _name = name;
    } else {
      _name = errors[_code].name;
    }
  }

  this.__defineGetter__('code', function() { return _code; });
  this.__defineGetter__('message', function() { return _message; });
  this.__defineGetter__('name', function() { return _name; });
};

for (var value in errors)
  Object.defineProperty(tizen.WebAPIError, errors[value].type, { value: value });

// NOTE: Stubs for Application. These are needed for running TCT until
// we have a proper Application API implementation.
exports.application = {
  getAppInfo: function() { return { id: 0 } }
};

exports.ApplicationControlData = function(key, value) {
  this.key = key;
  this.value = value;
};

exports.ApplicationControl = function(operation, uri, mime, category, data) {
  this.operation = operation;
  this.uri = uri;
  this.mime = mime;
  this.category = category;
  this.data = data || [];
};
<|endoftext|>


<commit_before>var propertyOperationStarted = false;

String.prototype.startsWith = function(prefix) {
	return this.indexOf(prefix) == 0;
}

function loadPropertiesDiv(resourcePath, page) {
	var fillingDiv = "resourceProperties";
	if ($('updateFix')) {
		$('updateFix').parentNode.removeChild($('updateFix'));
	}
	var tempSpan = document.createElement('span');
	tempSpan.id = "updateFix";
	sessionAwareFunction(function() {
		new Ajax.Request('../registry_vault/properties-ajaxprocessor.jsp', {
			method : 'post',
			parameters : {
				path : resourcePath,
				page : page
			},
			onSuccess : function(transport) {
				$(fillingDiv).innerHTML = transport.responseText;
				$('propertiesList').style.display = "";
				$('propertiesIconExpanded').style.display = "";
				$('propertiesIconMinimized').style.display = "none";

				YAHOO.util.Event.onAvailable('updateFix', function() {
					$('propertiesList').style.display = "";
				});
			},
			onFailure : function(transport) {
				showRegistryError(transport.responseText);
			}
		});
	}, org_wso2_carbon_registry_secure_vault_ui_jsi18n["session.timed.out"]);
}

function setProperty() {
	if (propertyOperationStarted) {
		CARBON
				.showWarningDialog(org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.operation.in.progress"]);
		return;
	}
	propertyOperationStarted = true;
	sessionAwareFunction(
			function() {

				var reason = "";
				reason += validateEmptySV(
						document.getElementById('propName'),
						org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name"]);
				// if (reason == "") {
				// reason
				// +=validateEmptySV(document.getElementById('propValue'),
				// org_wso2_carbon_mediation_secure_vault_ui_jsi18n["property.value"]);
				// }

				if (reason == "") {
					reason += validateForInputSV(
							document.getElementById('propName'),
							org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name"]);
				}
				if (reason == "") {
					reason += validateForInputSV(
							document.getElementById('propValue'),
							org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.value"]);
				}

				if(reason == ""){

					if(document.getElementById('propValue').value != document.getElementById('propValueConfirm').value){
						reason += org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.value.confirmation.invalid"];
					}
				}

				var propertyName = document.getElementById('propName').value;
				var propertyValue = document.getElementById('propValue').value;

				if (reason == "") {
					propertyName = propertyName.replace(/^\s\s*/, '').replace(
							/\s\s*$/, '');
					if (propertyName == "") {
						reason = org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.value.cannot.contain.only.white.spaces"];
					}

					propertyValue = propertyValue.replace(/^\s\s*/, '')
							.replace(/\s\s*$/, '');
					// if (propertyValue == "") {
					// reason =
					// org_wso2_carbon_mediation_secure_vault_ui_jsi18n["property.value.cannot.contain.only.white.spaces"];
					// }
				}

				if (propertyName.startsWith("registry.")) {
					reason = org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name.cannot.be.hidden"];
				}
				// Check for the previously entered property
				var foundPropName = false;
				var allNodes = document.getElementById("propertiesList")
						.getElementsByTagName("*");

				for ( var i = 0; i < allNodes.length; i++) {
					if (YAHOO.util.Dom.hasClass(allNodes[i],
							"propEditNameSelector")) {
						if (allNodes[i].value == $('propName').value)
							reason += org_wso2_carbon_registry_secure_vault_ui_jsi18n["duplicate.entry.please.choose.another.name"];
					}
				}

				if (reason != "") {
					CARBON.showWarningDialog(reason);
					return false;
				} else {
  					//alert("about to submit1");
					cleanField($('propName'));
					cleanField($('propValue'));
					new Ajax.Request(
							'../registry_vault/properties-ajaxprocessor.jsp',
							{
								method : 'post',
								parameters : {
									name : propertyName,
									value : propertyValue
								},

								onSuccess : function(transport) {
									window.location.reload();

								},

								onFailure : function(transport) {
									CARBON
											.showErrorDialog(transport.responseText);
									propertyOperationStarted = false;
									return;
								}
							});
					showHideCommon('propertiesAddDiv');
				}
				return true;
			},
			org_wso2_carbon_registry_secure_vault_ui_jsi18n["session.timed.out"]);
	propertyOperationStarted = false;

}

function editProperty(rowid) {
	if (propertyOperationStarted) {
		CARBON
				.showWarningDialog(org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.operation.in.progress"]);
		return;
	}
	propertyOperationStarted = true;
	sessionAwareFunction(
			function() {
				var reason = "";

				var resourcePath = document
						.getElementById('propRPath_' + rowid).value;
				var oldPropertyName = document.getElementById('oldPropName_'
						+ rowid).value;
				var propertyName = document.getElementById('propName_' + rowid);
				reason += validateEmptySV(
						propertyName,
						org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name"]);
				reason += validateForInputSV(
						propertyName,
						org_wso2_carbon_registr_secure_vault_ui_jsi18n["property.name"]);
				var propertyValue = document.getElementById('propValue_'
						+ rowid);
				var propertyValueConfim = document.getElementById('propValueConfirm_'
						+ rowid);
				// reason +=
				// validateEmptySV(propertyValue,org_wso2_carbon_mediation_secure_vault_ui_jsi18n["property.value"]);
				reason += validateForInputSV(
						propertyValue,
						org_wso2_carbon_registr_secure_vault_ui_jsi18n["property.value"]);

				// Check for the previously entered property
				var duplicatePropNameCount = 0;
				var allNodes = document.getElementById("propertiesList")
						.getElementsByTagName("*");

				for ( var i = 0; i < allNodes.length; i++) {
					if (YAHOO.util.Dom.hasClass(allNodes[i],
							"propEditNameSelector")) {
						if (allNodes[i].value == propertyName.value) {
							duplicatePropNameCount = duplicatePropNameCount + 1;

						}
					}
				}

				if (duplicatePropNameCount > 1) {
					reason += org_wso2_carbon_registr_secure_vault_ui_jsi18n["duplicate.entry.please.choose.another.name"];
				}

				if(reason == ""){

					if(propertyValue.value != propertyValueConfim.value){
						reason += org_wso2_carbon_registr_secure_vault_ui_jsi18n["property.value.confirmation.invalid"];
					}
				}

				if (reason == "") {
					new Ajax.Request(
							'../registr_vault/properties-ajaxprocessor.jsp',
							{
								method : 'post',
								parameters : {
									path : resourcePath,
									oldName : oldPropertyName,
									name : propertyName.value,
									value : propertyValue.value
								},

								onSuccess : function(transport) {
									window.location.reload();
								},

								onFailure : function(transport) {
									CARBON
											.showErrorDialog(transport.responseText);
									propertyOperationStarted = false;
									return;
								}
							});
				} else {
					CARBON.showWarningDialog(reason,
							function() {
								$('propName_' + rowid).value = $('oldPropName_'
										+ rowid).value;
							});
				}
			},
			org_wso2_carbon_registr_secure_vault_ui_jsi18n["session.timed.out"]);
	propertyOperationStarted = false;
}

function removeProperty(propertyName) {
	if (propertyOperationStarted) {
		CARBON
				.showWarningDialog(org_wso2_carbon_registr_secure_vault_ui_jsi18n["property.operation.in.progress"]);
		return;
	}
	propertyOperationStarted = true;
	sessionAwareFunction(
			function() {
				CARBON
						.showConfirmationDialog(
								org_wso2_carbon_registr_secure_vault_ui_jsi18n["are.you.sure.you.want.to.delete"]
										+ " '"
										+ propertyName
										+ "' "
										+ org_wso2_carbon_registr_secure_vault_ui_jsi18n["permanently"],
								function() {
									var resourcePath = document
											.getElementById('propRPath').value;
									new Ajax.Request(
											'../registr_vault/properties-ajaxprocessor.jsp',
											{
												method : 'post',
												parameters : {
													path : resourcePath,
													name : propertyName,
													remove : 'true'
												},

												onSuccess : function(transport) {
													window.location.reload();
												},

												onFailure : function(transport) {
													CARBON
															.showErrorDialog(transport.responseText);
													propertyOperationStarted = false;
													return;
												}
											});
								}, null);
			},
			org_wso2_carbon_registr_secure_vault_ui_jsi18n["session.timed.out"]);
	propertyOperationStarted = false;
}
function showProperties() {
	if ($('propertiesIconExpanded').style.display == "none") {
		// We have to expand all and hide sum
		$('propertiesIconExpanded').style.display = "";
		$('propertiesIconMinimized').style.display = "none";
		$('propertiesExpanded').style.display = "";
		$('propertiesMinimized').style.display = "none";
	} else {
		$('propertiesIconExpanded').style.display = "none";
		$('propertiesIconMinimized').style.display = "";
		$('propertiesExpanded').style.display = "none";
		$('propertiesMinimized').style.display = "";
	}
}

function showRetention() {
	if ($('retentionIconExpanded').style.display == "none") {
		// We have to expand all and hide sum
		$('retentionIconExpanded').style.display = "";
		$('retentionIconMinimized').style.display = "none";
		$('retentionExpanded').style.display = "";
		$('retentionMinimized').style.display = "none";
	} else {
		$('retentionIconExpanded').style.display = "none";
		$('retentionIconMinimized').style.display = "";
		$('retentionExpanded').style.display = "none";
		$('retentionMinimized').style.display = "";
	}
}

function validateEmptySV(fld, fldName) {
	var error = "";
	fld.value = fld.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

	if (fld.value.length == 0) {
		error = "The required field" + " " + fldName + " " + "Not fild"
				+ "
";
	} else {
		// fld.style.background = 'White';
	}
	return error;
}

function validateForInputSV(fld, fldName) {
  	var error = "";
	var illegalChars = /(\<[a-zA-Z0-9\s\/]*>)/; // match any starting tag
	if (illegalChars.test(fld.value)) {
		error = "The"
				+ " "
				+ fldName
				+ " "
				+"has illigal charachters"
				+ "
";
	} else {
		// fld.style.background = 'White';
	}
 	//alert("validate input done");
	return error;
}
function validateValueForInputSV(fldValue, fldName) {
	var error = "";
	var illegalChars = /(\<[a-zA-Z0-9\s\/]*>)/; // match any starting tag
	if (illegalChars.test(fldValue)) {
		error = org_wso2_carbon_registry_common_ui_jsi18n["the"]
				+ " "
				+ fldName
				+ " "
				+ org_wso2_carbon_registry_common_ui_jsi18n["input.contains.illegal.chars"]
				+ "
";
	}
	return error;
}<commit_msg>REGISTRY-2769 Fixing delete operation of secure vault tool<commit_after>var propertyOperationStarted = false;

String.prototype.startsWith = function(prefix) {
	return this.indexOf(prefix) == 0;
}

function loadPropertiesDiv(resourcePath, page) {
	var fillingDiv = "resourceProperties";
	if ($('updateFix')) {
		$('updateFix').parentNode.removeChild($('updateFix'));
	}
	var tempSpan = document.createElement('span');
	tempSpan.id = "updateFix";
	sessionAwareFunction(function() {
		new Ajax.Request('../registry_vault/properties-ajaxprocessor.jsp', {
			method : 'post',
			parameters : {
				path : resourcePath,
				page : page
			},
			onSuccess : function(transport) {
				$(fillingDiv).innerHTML = transport.responseText;
				$('propertiesList').style.display = "";
				$('propertiesIconExpanded').style.display = "";
				$('propertiesIconMinimized').style.display = "none";

				YAHOO.util.Event.onAvailable('updateFix', function() {
					$('propertiesList').style.display = "";
				});
			},
			onFailure : function(transport) {
				showRegistryError(transport.responseText);
			}
		});
	}, org_wso2_carbon_registry_secure_vault_ui_jsi18n["session.timed.out"]);
}

function setProperty() {
	if (propertyOperationStarted) {
		CARBON
				.showWarningDialog(org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.operation.in.progress"]);
		return;
	}
	propertyOperationStarted = true;
	sessionAwareFunction(
			function() {

				var reason = "";
				reason += validateEmptySV(
						document.getElementById('propName'),
						org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name"]);
				// if (reason == "") {
				// reason
				// +=validateEmptySV(document.getElementById('propValue'),
				// org_wso2_carbon_mediation_secure_vault_ui_jsi18n["property.value"]);
				// }

				if (reason == "") {
					reason += validateForInputSV(
							document.getElementById('propName'),
							org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name"]);
				}
				if (reason == "") {
					reason += validateForInputSV(
							document.getElementById('propValue'),
							org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.value"]);
				}

				if(reason == ""){

					if(document.getElementById('propValue').value != document.getElementById('propValueConfirm').value){
						reason += org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.value.confirmation.invalid"];
					}
				}

				var propertyName = document.getElementById('propName').value;
				var propertyValue = document.getElementById('propValue').value;

				if (reason == "") {
					propertyName = propertyName.replace(/^\s\s*/, '').replace(
							/\s\s*$/, '');
					if (propertyName == "") {
						reason = org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.value.cannot.contain.only.white.spaces"];
					}

					propertyValue = propertyValue.replace(/^\s\s*/, '')
							.replace(/\s\s*$/, '');
					// if (propertyValue == "") {
					// reason =
					// org_wso2_carbon_mediation_secure_vault_ui_jsi18n["property.value.cannot.contain.only.white.spaces"];
					// }
				}

				if (propertyName.startsWith("registry.")) {
					reason = org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name.cannot.be.hidden"];
				}
				// Check for the previously entered property
				var foundPropName = false;
				var allNodes = document.getElementById("propertiesList")
						.getElementsByTagName("*");

				for ( var i = 0; i < allNodes.length; i++) {
					if (YAHOO.util.Dom.hasClass(allNodes[i],
							"propEditNameSelector")) {
						if (allNodes[i].value == $('propName').value)
							reason += org_wso2_carbon_registry_secure_vault_ui_jsi18n["duplicate.entry.please.choose.another.name"];
					}
				}

				if (reason != "") {
					CARBON.showWarningDialog(reason);
					return false;
				} else {
  					//alert("about to submit1");
					cleanField($('propName'));
					cleanField($('propValue'));
					new Ajax.Request(
							'../registry_vault/properties-ajaxprocessor.jsp',
							{
								method : 'post',
								parameters : {
									name : propertyName,
									value : propertyValue
								},

								onSuccess : function(transport) {
									window.location.reload();

								},

								onFailure : function(transport) {
									CARBON
											.showErrorDialog(transport.responseText);
									propertyOperationStarted = false;
									return;
								}
							});
					showHideCommon('propertiesAddDiv');
				}
				return true;
			},
			org_wso2_carbon_registry_secure_vault_ui_jsi18n["session.timed.out"]);
	propertyOperationStarted = false;

}

function editProperty(rowid) {
	if (propertyOperationStarted) {
		CARBON
				.showWarningDialog(org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.operation.in.progress"]);
		return;
	}
	propertyOperationStarted = true;
	sessionAwareFunction(
			function() {
				var reason = "";

				var resourcePath = document
						.getElementById('propRPath_' + rowid).value;
				var oldPropertyName = document.getElementById('oldPropName_'
						+ rowid).value;
				var propertyName = document.getElementById('propName_' + rowid);
				reason += validateEmptySV(
						propertyName,
						org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name"]);
				reason += validateForInputSV(
						propertyName,
						org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.name"]);
				var propertyValue = document.getElementById('propValue_'
						+ rowid);
				var propertyValueConfim = document.getElementById('propValueConfirm_'
						+ rowid);
				// reason +=
				// validateEmptySV(propertyValue,org_wso2_carbon_mediation_secure_vault_ui_jsi18n["property.value"]);
				reason += validateForInputSV(
						propertyValue,
						org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.value"]);

				// Check for the previously entered property
				var duplicatePropNameCount = 0;
				var allNodes = document.getElementById("propertiesList")
						.getElementsByTagName("*");

				for ( var i = 0; i < allNodes.length; i++) {
					if (YAHOO.util.Dom.hasClass(allNodes[i],
							"propEditNameSelector")) {
						if (allNodes[i].value == propertyName.value) {
							duplicatePropNameCount = duplicatePropNameCount + 1;

						}
					}
				}

				if (duplicatePropNameCount > 1) {
					reason += org_wso2_carbon_registry_secure_vault_ui_jsi18n["duplicate.entry.please.choose.another.name"];
				}

				if(reason == ""){

					if(propertyValue.value != propertyValueConfim.value){
						reason += org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.value.confirmation.invalid"];
					}
				}

				if (reason == "") {
					new Ajax.Request(
							'../registry_vault/properties-ajaxprocessor.jsp',
							{
								method : 'post',
								parameters : {
									path : resourcePath,
									oldName : oldPropertyName,
									name : propertyName.value,
									value : propertyValue.value
								},

								onSuccess : function(transport) {
									window.location.reload();
								},

								onFailure : function(transport) {
									CARBON
											.showErrorDialog(transport.responseText);
									propertyOperationStarted = false;
									return;
								}
							});
				} else {
					CARBON.showWarningDialog(reason,
							function() {
								$('propName_' + rowid).value = $('oldPropName_'
										+ rowid).value;
							});
				}
			},
			org_wso2_carbon_registry_secure_vault_ui_jsi18n["session.timed.out"]);
	propertyOperationStarted = false;
}

function removeProperty(propertyName) {
	if (propertyOperationStarted) {
		CARBON
				.showWarningDialog(org_wso2_carbon_registry_secure_vault_ui_jsi18n["property.operation.in.progress"]);
		return;
	}

	propertyOperationStarted = true;
	sessionAwareFunction(
			function() {
				CARBON
						.showConfirmationDialog(
								org_wso2_carbon_registry_secure_vault_ui_jsi18n["are.you.sure.you.want.to.delete"]
										+ " '"
										+ propertyName
										+ "' "
										+ org_wso2_carbon_registry_secure_vault_ui_jsi18n["permanently"],
								function() {
									var resourcePath = document
											.getElementById('propRPath').value;
									new Ajax.Request(
											'../registry_vault/properties-ajaxprocessor.jsp',
											{
												method : 'post',
												parameters : {
													path : resourcePath,
													name : propertyName,
													remove : 'true'
												},

												onSuccess : function(transport) {
													window.location.reload();
												},

												onFailure : function(transport) {
													CARBON
															.showErrorDialog(transport.responseText);
													propertyOperationStarted = false;
													return;
												}
											});
								}, null);
			},
			org_wso2_carbon_registry_secure_vault_ui_jsi18n["session.timed.out"]);
	propertyOperationStarted = false;
}
function showProperties() {
	if ($('propertiesIconExpanded').style.display == "none") {
		// We have to expand all and hide sum
		$('propertiesIconExpanded').style.display = "";
		$('propertiesIconMinimized').style.display = "none";
		$('propertiesExpanded').style.display = "";
		$('propertiesMinimized').style.display = "none";
	} else {
		$('propertiesIconExpanded').style.display = "none";
		$('propertiesIconMinimized').style.display = "";
		$('propertiesExpanded').style.display = "none";
		$('propertiesMinimized').style.display = "";
	}
}

function showRetention() {
	if ($('retentionIconExpanded').style.display == "none") {
		// We have to expand all and hide sum
		$('retentionIconExpanded').style.display = "";
		$('retentionIconMinimized').style.display = "none";
		$('retentionExpanded').style.display = "";
		$('retentionMinimized').style.display = "none";
	} else {
		$('retentionIconExpanded').style.display = "none";
		$('retentionIconMinimized').style.display = "";
		$('retentionExpanded').style.display = "none";
		$('retentionMinimized').style.display = "";
	}
}

function validateEmptySV(fld, fldName) {
	var error = "";
	fld.value = fld.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

	if (fld.value.length == 0) {
		error = "The required field" + " " + fldName + " " + "Not fild"
				+ "
";
	} else {
		// fld.style.background = 'White';
	}
	return error;
}

function validateForInputSV(fld, fldName) {
  	var error = "";
	var illegalChars = /(\<[a-zA-Z0-9\s\/]*>)/; // match any starting tag
	if (illegalChars.test(fld.value)) {
		error = "The"
				+ " "
				+ fldName
				+ " "
				+"has illigal charachters"
				+ "
";
	} else {
		// fld.style.background = 'White';
	}
 	//alert("validate input done");
	return error;
}
function validateValueForInputSV(fldValue, fldName) {
	var error = "";
	var illegalChars = /(\<[a-zA-Z0-9\s\/]*>)/; // match any starting tag
	if (illegalChars.test(fldValue)) {
		error = org_wso2_carbon_registry_common_ui_jsi18n["the"]
				+ " "
				+ fldName
				+ " "
				+ org_wso2_carbon_registry_common_ui_jsi18n["input.contains.illegal.chars"]
				+ "
";
	}
	return error;
}<|endoftext|>


<commit_before><commit_msg>add fixes about transformOrigin on animation source creating<commit_after><|endoftext|>


<commit_before>/**
 * @name Auth.js
 * @version 1.0.0
 * @author Karl Moad <github.com/karlmoad>
 *
 *  A javascript class library that encapsulates the implementation of Single Page Application
 *  Authentication and Authorization Processes with Active Directory and authorization sources.  Azure
 *  Active Directory is configured to include an application for use by this library.  Client application
 *  then first authenticate to the Azure endpoint utilizing the OAuth Implcit Grant/FLow then submit the resulting
 *  token form the Azure results to the defined authoirzation source for a final authorization token. The Authorization
 *  token will be retained in browser storage for later use
 *
 *  @summary use Azure Active Directory to get an authentication token and exchane this token for an authorization token from the defined service
 */
(function(){

})();<commit_msg>updates to base code<commit_after>/**
 * @name Auth.js
 * @version 1.0.0
 * @author Karl Moad <github.com/karlmoad>
 *
 *  A javascript class library that encapsulates the implementation of Single Page Application
 *  Authentication and Authorization Processes with Active Directory and authorization sources.  Azure
 *  Active Directory is configured to include an application for use by this library.  Client application
 *  then first authenticate to the Azure endpoint utilizing the OAuth Implcit Grant/FLow then submit the resulting
 *  token form the Azure results to the defined authoirzation source for a final authorization token. The Authorization
 *  token will be retained in browser storage for later use
 *
 *  @summary use Azure Active Directory to get an authentication token and exchange it for an authorization token from the defined service
 */
var AuthContext = (function(){
    'use strict'

    AuthContext = function(config){

    };

    if (typeof module !== 'undefined' && module.exports) {
        module.exports = AuthContext;
        module.exports.inject = function (options) {
            return new AuthContext(options);
        };
    }

    return AuthContext;
}());<|endoftext|>


<commit_before>import Ember from 'ember';
//import D3Component from './d3-component';
import D3Group from './d3-group';

const { computed, observer } = Ember;

export default D3Group.extend({
  attributeBindings: ['transform', 'clip-path'],

  'clip-path': computed('parentView.clipPath', function() {
    return `url(${this.get('parentView.clipPath')})`;
  })
});
<commit_msg>Fix clip-path URL<commit_after>import Ember from 'ember';
//import D3Component from './d3-component';
import D3Group from './d3-group';

const { computed, observer } = Ember;

export default D3Group.extend({
  attributeBindings: ['transform', 'clip-path'],

  'clip-path': computed('parentView.clipPath', function() {
    return `url(${window.location.href}${this.get('parentView.clipPath')})`;
  })
});
<|endoftext|>