<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * 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.
 *
 *******************************************************************************/
#ifndef GUARD_MIOPEN_TENSOR_OPPS_HPP_
#define GUARD_MIOPEN_TENSOR_OPPS_HPP_

#include <miopen/common.hpp>
#include <miopen/datatype.hpp>
#include <miopen/handle.hpp>
#include <miopen/miopen.h>
#include <miopen/object.hpp>
#include <vector>

namespace miopen {

void ScaleTensor(Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, const int offset = 0);

void SetTensor(Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, const int offset = 0);

void OpTensor(Handle& handle,
              miopenTensorOp_t tensorOp,
              const void* alpha0,
              const TensorDescriptor& aTensorDesc,
              ConstData_t ATensor,
              const void* alpha1,
              const TensorDescriptor& bTensorDesc,
              ConstData_t BTensor,
              const void* beta,
              const TensorDescriptor& cTensorDesc,
              Data_t CTensor,
              size_t Aoffset = 0,
              size_t Boffset = 0,
              size_t Coffset = 0);

void CopyTensor(Handle& handle,
                const TensorDescriptor& srcDesc,
                ConstData_t src,
                const TensorDescriptor& destDesc,
                Data_t dest,
                int srcOffset  = 0,
                int destOffset = 0);

} // namespace miopen
#endif // GUARD_MIOPEN_TENSOR_OPPS_HPP_
<commit_msg>fix clang-tidy errors<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * 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.
 *
 *******************************************************************************/
#ifndef GUARD_MIOPEN_TENSOR_OPPS_HPP_
#define GUARD_MIOPEN_TENSOR_OPPS_HPP_

#include <miopen/common.hpp>
#include <miopen/datatype.hpp>
#include <miopen/handle.hpp>
#include <miopen/miopen.h>
#include <miopen/object.hpp>
#include <vector>

namespace miopen {

void ScaleTensor(Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, int offset = 0);

void SetTensor(Handle& handle, const TensorDescriptor& yDesc, Data_t y, const void* alpha, int offset = 0);

void OpTensor(Handle& handle,
              miopenTensorOp_t tensorOp,
              const void* alpha0,
              const TensorDescriptor& aTensorDesc,
              ConstData_t ATensor,
              const void* alpha1,
              const TensorDescriptor& bTensorDesc,
              ConstData_t BTensor,
              const void* beta,
              const TensorDescriptor& cTensorDesc,
              Data_t CTensor,
              size_t Aoffset = 0,
              size_t Boffset = 0,
              size_t Coffset = 0);

void CopyTensor(Handle& handle,
                const TensorDescriptor& srcDesc,
                ConstData_t src,
                const TensorDescriptor& dstDesc,
                Data_t dst,
                int srcOffset  = 0,
                int dstOffset = 0);

} // namespace miopen
#endif // GUARD_MIOPEN_TENSOR_OPPS_HPP_
<|endoftext|>


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

#include "chrome/browser/content_settings/content_settings_notification_provider.h"

#include "base/string_util.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "googleurl/src/gurl.h"

namespace {

const ContentSetting kDefaultSetting = CONTENT_SETTING_ASK;

}  // namespace

namespace content_settings {

// ////////////////////////////////////////////////////////////////////////////
// NotificationProvider
//

// static
void NotificationProvider::RegisterUserPrefs(PrefService* user_prefs) {
  if (!user_prefs->FindPreference(prefs::kDesktopNotificationAllowedOrigins))
    user_prefs->RegisterListPref(prefs::kDesktopNotificationAllowedOrigins);
  if (!user_prefs->FindPreference(prefs::kDesktopNotificationDeniedOrigins))
    user_prefs->RegisterListPref(prefs::kDesktopNotificationDeniedOrigins);
}

// TODO(markusheintz): Re-factoring in progress. Do not move or touch the
// following two static methods as you might cause trouble. Thanks!

// static
ContentSettingsPattern NotificationProvider::ToContentSettingsPattern(
    const GURL& origin) {
  // Fix empty GURLs.
  if (origin.spec().empty()) {
    std::string pattern_spec(chrome::kFileScheme);
    pattern_spec += chrome::kStandardSchemeSeparator;
    return ContentSettingsPattern(pattern_spec);
  }
  return ContentSettingsPattern::FromURLNoWildcard(origin);
}

// static
GURL NotificationProvider::ToGURL(const ContentSettingsPattern& pattern) {
  std::string pattern_spec(pattern.AsString());

  if (pattern_spec.empty() ||
      StartsWithASCII(pattern_spec,
                      std::string(ContentSettingsPattern::kDomainWildcard),
                      true)) {
    NOTREACHED();
  }

  std::string url_spec("");
  if (StartsWithASCII(pattern_spec, std::string(chrome::kFileScheme), false)) {
    url_spec += pattern_spec;
  } else if (!pattern.scheme().empty()) {
    url_spec += pattern.scheme();
    url_spec += chrome::kStandardSchemeSeparator;
    url_spec += pattern_spec;
  }

  LOG(ERROR) << " url_spec=" << url_spec;
  return GURL(url_spec);
}

NotificationProvider::NotificationProvider(
    Profile* profile)
    : profile_(profile) {
  prefs_registrar_.Init(profile_->GetPrefs());
  StartObserving();
}

NotificationProvider::~NotificationProvider() {
  StopObserving();
}

bool NotificationProvider::ContentSettingsTypeIsManaged(
      ContentSettingsType content_type) {
  return false;
}

ContentSetting NotificationProvider::GetContentSetting(
      const GURL& requesting_url,
      const GURL& embedding_url,
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier) const {
  if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    return CONTENT_SETTING_DEFAULT;

  return GetContentSetting(requesting_url);
}

void NotificationProvider::SetContentSetting(
      const ContentSettingsPattern& requesting_url_pattern,
      const ContentSettingsPattern& embedding_url_pattern,
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier,
      ContentSetting content_setting) {
  if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    return;

  GURL origin = ToGURL(requesting_url_pattern);
  if (CONTENT_SETTING_ALLOW == content_setting) {
    GrantPermission(origin);
  } else if (CONTENT_SETTING_BLOCK == content_setting) {
    DenyPermission(origin);
  } else if (CONTENT_SETTING_DEFAULT == content_setting) {
    ContentSetting current_setting = GetContentSetting(origin);
    if (CONTENT_SETTING_ALLOW == current_setting) {
      ResetAllowedOrigin(origin);
    } else if (CONTENT_SETTING_BLOCK == current_setting) {
      ResetBlockedOrigin(origin);
    } else {
      NOTREACHED();
    }
  } else {
      NOTREACHED();
  }
}

void NotificationProvider::GetAllContentSettingsRules(
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier,
      Rules* content_setting_rules) const {
  if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    return;

  std::vector<GURL> allowed_origins = GetAllowedOrigins();
  std::vector<GURL> denied_origins = GetBlockedOrigins();

  for (std::vector<GURL>::iterator url = allowed_origins.begin();
       url != allowed_origins.end();
       ++url) {
    ContentSettingsPattern pattern =
        ContentSettingsPattern::FromURLNoWildcard(*url);
    content_setting_rules->push_back(Rule(
        pattern,
        pattern,
        CONTENT_SETTING_ALLOW));
  }
  for (std::vector<GURL>::iterator url = denied_origins.begin();
       url != denied_origins.end();
       ++url) {
    ContentSettingsPattern pattern =
        ContentSettingsPattern::FromURLNoWildcard(*url);
    content_setting_rules->push_back(Rule(
        pattern,
        pattern,
        CONTENT_SETTING_BLOCK));
  }
}

void NotificationProvider::ClearAllContentSettingsRules(
      ContentSettingsType content_type) {
  if (content_type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    ResetAllOrigins();
}

void NotificationProvider::ResetToDefaults() {
  ResetAllOrigins();
}

void NotificationProvider::Observe(NotificationType type,
                                   const NotificationSource& source,
                                   const NotificationDetails& details) {
  if (NotificationType::PREF_CHANGED == type) {
    const std::string& name = *Details<std::string>(details).ptr();
    OnPrefsChanged(name);
  } else if (NotificationType::PROFILE_DESTROYED == type) {
    StopObserving();
  }
}

/////////////////////////////////////////////////////////////////////
// Private
//

void NotificationProvider::StartObserving() {
  if (!profile_->IsOffTheRecord()) {
    prefs_registrar_.Add(prefs::kDesktopNotificationDefaultContentSetting,
                         this);
    prefs_registrar_.Add(prefs::kDesktopNotificationAllowedOrigins, this);
    prefs_registrar_.Add(prefs::kDesktopNotificationDeniedOrigins, this);

    notification_registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
                                NotificationService::AllSources());
  }

  notification_registrar_.Add(this, NotificationType::PROFILE_DESTROYED,
                              Source<Profile>(profile_));
}

void NotificationProvider::StopObserving() {
  if (!profile_->IsOffTheRecord()) {
    prefs_registrar_.RemoveAll();
  }
  notification_registrar_.RemoveAll();
}

void NotificationProvider::OnPrefsChanged(const std::string& pref_name) {
  if (pref_name == prefs::kDesktopNotificationAllowedOrigins) {
    NotifySettingsChange();
  } else if (pref_name == prefs::kDesktopNotificationDeniedOrigins) {
    NotifySettingsChange();
  }
}

void NotificationProvider::NotifySettingsChange() {
  // TODO(markusheintz): Re-factoring work in progress: Replace the
  // DESKTOP_NOTIFICATION_SETTINGS_CHANGED with a CONTENT_SETTINGS_CHANGED
  // notification, and use the HostContentSettingsMap as source once this
  // content settings provider in integrated in the HostContentSetttingsMap.
  NotificationService::current()->Notify(
      NotificationType::DESKTOP_NOTIFICATION_SETTINGS_CHANGED,
      Source<DesktopNotificationService>(
          profile_->GetDesktopNotificationService()),
      NotificationService::NoDetails());
}

std::vector<GURL> NotificationProvider::GetAllowedOrigins() const {
  std::vector<GURL> allowed_origins;
  PrefService* prefs = profile_->GetPrefs();
  const ListValue* allowed_sites =
      prefs->GetList(prefs::kDesktopNotificationAllowedOrigins);
  if (allowed_sites) {
    // TODO(markusheintz): Remove dependency to PrefsCache
    NotificationsPrefsCache::ListValueToGurlVector(*allowed_sites,
                                                   &allowed_origins);
  }
  return allowed_origins;
}

std::vector<GURL> NotificationProvider::GetBlockedOrigins() const {
  std::vector<GURL> denied_origins;
  PrefService* prefs = profile_->GetPrefs();
  const ListValue* denied_sites =
      prefs->GetList(prefs::kDesktopNotificationDeniedOrigins);
  if (denied_sites) {
     // TODO(markusheintz): Remove dependency to PrefsCache
    NotificationsPrefsCache::ListValueToGurlVector(*denied_sites,
                                                   &denied_origins);
  }
  return denied_origins;
}

void NotificationProvider::GrantPermission(const GURL& origin) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  PersistPermissionChange(origin, true);
  NotifySettingsChange();
}

void NotificationProvider::DenyPermission(const GURL& origin) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  PersistPermissionChange(origin, false);
  NotifySettingsChange();
}

void NotificationProvider::PersistPermissionChange(
    const GURL& origin, bool is_allowed) {
  // Don't persist changes when off the record.
  if (profile_->IsOffTheRecord())
    return;
  PrefService* prefs = profile_->GetPrefs();

  // |Observe()| updates the whole permission set in the cache, but only a
  // single origin has changed. Hence, callers of this method manually
  // schedule a task to update the prefs cache, and the prefs observer is
  // disabled while the update runs.
  StopObserving();

  bool allowed_changed = false;
  bool denied_changed = false;

  ListValue* allowed_sites =
      prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
  ListValue* denied_sites =
      prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
  {
    // |value| is passed to the preferences list, or deleted.
    StringValue* value = new StringValue(origin.spec());

    // Remove from one list and add to the other.
    if (is_allowed) {
      // Remove from the denied list.
      if (denied_sites->Remove(*value) != -1)
        denied_changed = true;

      // Add to the allowed list.
      if (allowed_sites->AppendIfNotPresent(value))
        allowed_changed = true;
    } else {
      // Remove from the allowed list.
      if (allowed_sites->Remove(*value) != -1)
        allowed_changed = true;

      // Add to the denied list.
      if (denied_sites->AppendIfNotPresent(value))
        denied_changed = true;
    }
  }

  // Persist the pref if anthing changed, but only send updates for the
  // list that changed.
  if (allowed_changed || denied_changed) {
    if (allowed_changed) {
      ScopedUserPrefUpdate update_allowed(
          prefs, prefs::kDesktopNotificationAllowedOrigins);
    }
    if (denied_changed) {
      ScopedUserPrefUpdate updateDenied(
          prefs, prefs::kDesktopNotificationDeniedOrigins);
    }
    prefs->ScheduleSavePersistentPrefs();
  }
  StartObserving();
}

ContentSetting NotificationProvider::GetContentSetting(
    const GURL& origin) const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (profile_->IsOffTheRecord())
    return kDefaultSetting;

  std::vector<GURL> allowed_origins(GetAllowedOrigins());
  if (std::find(allowed_origins.begin(), allowed_origins.end(), origin) !=
      allowed_origins.end())
    return CONTENT_SETTING_ALLOW;

  std::vector<GURL> denied_origins(GetBlockedOrigins());
  if (std::find(denied_origins.begin(), denied_origins.end(), origin) !=
      denied_origins.end())
    return CONTENT_SETTING_BLOCK;

  return CONTENT_SETTING_DEFAULT;
}

void NotificationProvider::ResetAllowedOrigin(const GURL& origin) {
  if (profile_->IsOffTheRecord())
    return;

  // Since this isn't called often, let the normal observer behavior update the
  // cache in this case.
  PrefService* prefs = profile_->GetPrefs();
  ListValue* allowed_sites =
      prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
  {
    StringValue value(origin.spec());
    int removed_index = allowed_sites->Remove(value);
    DCHECK_NE(-1, removed_index) << origin << " was not allowed";
    ScopedUserPrefUpdate update_allowed(
        prefs, prefs::kDesktopNotificationAllowedOrigins);
  }
  prefs->ScheduleSavePersistentPrefs();
}

void NotificationProvider::ResetBlockedOrigin(const GURL& origin) {
  if (profile_->IsOffTheRecord())
    return;

  // Since this isn't called often, let the normal observer behavior update the
  // cache in this case.
  PrefService* prefs = profile_->GetPrefs();
  ListValue* denied_sites =
      prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
  {
    StringValue value(origin.spec());
    int removed_index = denied_sites->Remove(value);
    DCHECK_NE(-1, removed_index) << origin << " was not blocked";
    ScopedUserPrefUpdate update_allowed(
        prefs, prefs::kDesktopNotificationDeniedOrigins);
  }
  prefs->ScheduleSavePersistentPrefs();
}

void NotificationProvider::ResetAllOrigins() {
  PrefService* prefs = profile_->GetPrefs();
  prefs->ClearPref(prefs::kDesktopNotificationAllowedOrigins);
  prefs->ClearPref(prefs::kDesktopNotificationDeniedOrigins);
}

}  // namespace content_settings
<commit_msg>Remove unnecessary LOG statement.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/content_settings/content_settings_notification_provider.h"

#include "base/string_util.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "googleurl/src/gurl.h"

namespace {

const ContentSetting kDefaultSetting = CONTENT_SETTING_ASK;

}  // namespace

namespace content_settings {

// ////////////////////////////////////////////////////////////////////////////
// NotificationProvider
//

// static
void NotificationProvider::RegisterUserPrefs(PrefService* user_prefs) {
  if (!user_prefs->FindPreference(prefs::kDesktopNotificationAllowedOrigins))
    user_prefs->RegisterListPref(prefs::kDesktopNotificationAllowedOrigins);
  if (!user_prefs->FindPreference(prefs::kDesktopNotificationDeniedOrigins))
    user_prefs->RegisterListPref(prefs::kDesktopNotificationDeniedOrigins);
}

// TODO(markusheintz): Re-factoring in progress. Do not move or touch the
// following two static methods as you might cause trouble. Thanks!

// static
ContentSettingsPattern NotificationProvider::ToContentSettingsPattern(
    const GURL& origin) {
  // Fix empty GURLs.
  if (origin.spec().empty()) {
    std::string pattern_spec(chrome::kFileScheme);
    pattern_spec += chrome::kStandardSchemeSeparator;
    return ContentSettingsPattern(pattern_spec);
  }
  return ContentSettingsPattern::FromURLNoWildcard(origin);
}

// static
GURL NotificationProvider::ToGURL(const ContentSettingsPattern& pattern) {
  std::string pattern_spec(pattern.AsString());

  if (pattern_spec.empty() ||
      StartsWithASCII(pattern_spec,
                      std::string(ContentSettingsPattern::kDomainWildcard),
                      true)) {
    NOTREACHED();
  }

  std::string url_spec("");
  if (StartsWithASCII(pattern_spec, std::string(chrome::kFileScheme), false)) {
    url_spec += pattern_spec;
  } else if (!pattern.scheme().empty()) {
    url_spec += pattern.scheme();
    url_spec += chrome::kStandardSchemeSeparator;
    url_spec += pattern_spec;
  }

  return GURL(url_spec);
}

NotificationProvider::NotificationProvider(
    Profile* profile)
    : profile_(profile) {
  prefs_registrar_.Init(profile_->GetPrefs());
  StartObserving();
}

NotificationProvider::~NotificationProvider() {
  StopObserving();
}

bool NotificationProvider::ContentSettingsTypeIsManaged(
      ContentSettingsType content_type) {
  return false;
}

ContentSetting NotificationProvider::GetContentSetting(
      const GURL& requesting_url,
      const GURL& embedding_url,
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier) const {
  if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    return CONTENT_SETTING_DEFAULT;

  return GetContentSetting(requesting_url);
}

void NotificationProvider::SetContentSetting(
      const ContentSettingsPattern& requesting_url_pattern,
      const ContentSettingsPattern& embedding_url_pattern,
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier,
      ContentSetting content_setting) {
  if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    return;

  GURL origin = ToGURL(requesting_url_pattern);
  if (CONTENT_SETTING_ALLOW == content_setting) {
    GrantPermission(origin);
  } else if (CONTENT_SETTING_BLOCK == content_setting) {
    DenyPermission(origin);
  } else if (CONTENT_SETTING_DEFAULT == content_setting) {
    ContentSetting current_setting = GetContentSetting(origin);
    if (CONTENT_SETTING_ALLOW == current_setting) {
      ResetAllowedOrigin(origin);
    } else if (CONTENT_SETTING_BLOCK == current_setting) {
      ResetBlockedOrigin(origin);
    } else {
      NOTREACHED();
    }
  } else {
      NOTREACHED();
  }
}

void NotificationProvider::GetAllContentSettingsRules(
      ContentSettingsType content_type,
      const ResourceIdentifier& resource_identifier,
      Rules* content_setting_rules) const {
  if (content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    return;

  std::vector<GURL> allowed_origins = GetAllowedOrigins();
  std::vector<GURL> denied_origins = GetBlockedOrigins();

  for (std::vector<GURL>::iterator url = allowed_origins.begin();
       url != allowed_origins.end();
       ++url) {
    ContentSettingsPattern pattern =
        ContentSettingsPattern::FromURLNoWildcard(*url);
    content_setting_rules->push_back(Rule(
        pattern,
        pattern,
        CONTENT_SETTING_ALLOW));
  }
  for (std::vector<GURL>::iterator url = denied_origins.begin();
       url != denied_origins.end();
       ++url) {
    ContentSettingsPattern pattern =
        ContentSettingsPattern::FromURLNoWildcard(*url);
    content_setting_rules->push_back(Rule(
        pattern,
        pattern,
        CONTENT_SETTING_BLOCK));
  }
}

void NotificationProvider::ClearAllContentSettingsRules(
      ContentSettingsType content_type) {
  if (content_type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS)
    ResetAllOrigins();
}

void NotificationProvider::ResetToDefaults() {
  ResetAllOrigins();
}

void NotificationProvider::Observe(NotificationType type,
                                   const NotificationSource& source,
                                   const NotificationDetails& details) {
  if (NotificationType::PREF_CHANGED == type) {
    const std::string& name = *Details<std::string>(details).ptr();
    OnPrefsChanged(name);
  } else if (NotificationType::PROFILE_DESTROYED == type) {
    StopObserving();
  }
}

/////////////////////////////////////////////////////////////////////
// Private
//

void NotificationProvider::StartObserving() {
  if (!profile_->IsOffTheRecord()) {
    prefs_registrar_.Add(prefs::kDesktopNotificationDefaultContentSetting,
                         this);
    prefs_registrar_.Add(prefs::kDesktopNotificationAllowedOrigins, this);
    prefs_registrar_.Add(prefs::kDesktopNotificationDeniedOrigins, this);

    notification_registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
                                NotificationService::AllSources());
  }

  notification_registrar_.Add(this, NotificationType::PROFILE_DESTROYED,
                              Source<Profile>(profile_));
}

void NotificationProvider::StopObserving() {
  if (!profile_->IsOffTheRecord()) {
    prefs_registrar_.RemoveAll();
  }
  notification_registrar_.RemoveAll();
}

void NotificationProvider::OnPrefsChanged(const std::string& pref_name) {
  if (pref_name == prefs::kDesktopNotificationAllowedOrigins) {
    NotifySettingsChange();
  } else if (pref_name == prefs::kDesktopNotificationDeniedOrigins) {
    NotifySettingsChange();
  }
}

void NotificationProvider::NotifySettingsChange() {
  // TODO(markusheintz): Re-factoring work in progress: Replace the
  // DESKTOP_NOTIFICATION_SETTINGS_CHANGED with a CONTENT_SETTINGS_CHANGED
  // notification, and use the HostContentSettingsMap as source once this
  // content settings provider in integrated in the HostContentSetttingsMap.
  NotificationService::current()->Notify(
      NotificationType::DESKTOP_NOTIFICATION_SETTINGS_CHANGED,
      Source<DesktopNotificationService>(
          profile_->GetDesktopNotificationService()),
      NotificationService::NoDetails());
}

std::vector<GURL> NotificationProvider::GetAllowedOrigins() const {
  std::vector<GURL> allowed_origins;
  PrefService* prefs = profile_->GetPrefs();
  const ListValue* allowed_sites =
      prefs->GetList(prefs::kDesktopNotificationAllowedOrigins);
  if (allowed_sites) {
    // TODO(markusheintz): Remove dependency to PrefsCache
    NotificationsPrefsCache::ListValueToGurlVector(*allowed_sites,
                                                   &allowed_origins);
  }
  return allowed_origins;
}

std::vector<GURL> NotificationProvider::GetBlockedOrigins() const {
  std::vector<GURL> denied_origins;
  PrefService* prefs = profile_->GetPrefs();
  const ListValue* denied_sites =
      prefs->GetList(prefs::kDesktopNotificationDeniedOrigins);
  if (denied_sites) {
     // TODO(markusheintz): Remove dependency to PrefsCache
    NotificationsPrefsCache::ListValueToGurlVector(*denied_sites,
                                                   &denied_origins);
  }
  return denied_origins;
}

void NotificationProvider::GrantPermission(const GURL& origin) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  PersistPermissionChange(origin, true);
  NotifySettingsChange();
}

void NotificationProvider::DenyPermission(const GURL& origin) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  PersistPermissionChange(origin, false);
  NotifySettingsChange();
}

void NotificationProvider::PersistPermissionChange(
    const GURL& origin, bool is_allowed) {
  // Don't persist changes when off the record.
  if (profile_->IsOffTheRecord())
    return;
  PrefService* prefs = profile_->GetPrefs();

  // |Observe()| updates the whole permission set in the cache, but only a
  // single origin has changed. Hence, callers of this method manually
  // schedule a task to update the prefs cache, and the prefs observer is
  // disabled while the update runs.
  StopObserving();

  bool allowed_changed = false;
  bool denied_changed = false;

  ListValue* allowed_sites =
      prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
  ListValue* denied_sites =
      prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
  {
    // |value| is passed to the preferences list, or deleted.
    StringValue* value = new StringValue(origin.spec());

    // Remove from one list and add to the other.
    if (is_allowed) {
      // Remove from the denied list.
      if (denied_sites->Remove(*value) != -1)
        denied_changed = true;

      // Add to the allowed list.
      if (allowed_sites->AppendIfNotPresent(value))
        allowed_changed = true;
    } else {
      // Remove from the allowed list.
      if (allowed_sites->Remove(*value) != -1)
        allowed_changed = true;

      // Add to the denied list.
      if (denied_sites->AppendIfNotPresent(value))
        denied_changed = true;
    }
  }

  // Persist the pref if anthing changed, but only send updates for the
  // list that changed.
  if (allowed_changed || denied_changed) {
    if (allowed_changed) {
      ScopedUserPrefUpdate update_allowed(
          prefs, prefs::kDesktopNotificationAllowedOrigins);
    }
    if (denied_changed) {
      ScopedUserPrefUpdate updateDenied(
          prefs, prefs::kDesktopNotificationDeniedOrigins);
    }
    prefs->ScheduleSavePersistentPrefs();
  }
  StartObserving();
}

ContentSetting NotificationProvider::GetContentSetting(
    const GURL& origin) const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (profile_->IsOffTheRecord())
    return kDefaultSetting;

  std::vector<GURL> allowed_origins(GetAllowedOrigins());
  if (std::find(allowed_origins.begin(), allowed_origins.end(), origin) !=
      allowed_origins.end())
    return CONTENT_SETTING_ALLOW;

  std::vector<GURL> denied_origins(GetBlockedOrigins());
  if (std::find(denied_origins.begin(), denied_origins.end(), origin) !=
      denied_origins.end())
    return CONTENT_SETTING_BLOCK;

  return CONTENT_SETTING_DEFAULT;
}

void NotificationProvider::ResetAllowedOrigin(const GURL& origin) {
  if (profile_->IsOffTheRecord())
    return;

  // Since this isn't called often, let the normal observer behavior update the
  // cache in this case.
  PrefService* prefs = profile_->GetPrefs();
  ListValue* allowed_sites =
      prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);
  {
    StringValue value(origin.spec());
    int removed_index = allowed_sites->Remove(value);
    DCHECK_NE(-1, removed_index) << origin << " was not allowed";
    ScopedUserPrefUpdate update_allowed(
        prefs, prefs::kDesktopNotificationAllowedOrigins);
  }
  prefs->ScheduleSavePersistentPrefs();
}

void NotificationProvider::ResetBlockedOrigin(const GURL& origin) {
  if (profile_->IsOffTheRecord())
    return;

  // Since this isn't called often, let the normal observer behavior update the
  // cache in this case.
  PrefService* prefs = profile_->GetPrefs();
  ListValue* denied_sites =
      prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);
  {
    StringValue value(origin.spec());
    int removed_index = denied_sites->Remove(value);
    DCHECK_NE(-1, removed_index) << origin << " was not blocked";
    ScopedUserPrefUpdate update_allowed(
        prefs, prefs::kDesktopNotificationDeniedOrigins);
  }
  prefs->ScheduleSavePersistentPrefs();
}

void NotificationProvider::ResetAllOrigins() {
  PrefService* prefs = profile_->GetPrefs();
  prefs->ClearPref(prefs::kDesktopNotificationAllowedOrigins);
  prefs->ClearPref(prefs::kDesktopNotificationDeniedOrigins);
}

}  // namespace content_settings
<|endoftext|>


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

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/ref_counted.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

class RenderViewHostManagerTest : public InProcessBrowserTest {
 public:
  RenderViewHostManagerTest() {
    EnableDOMAutomation();
  }

  static bool GetFilePathWithHostAndPortReplacement(
      const std::string& original_file_path,
      const net::HostPortPair& host_port_pair,
      std::string* replacement_path) {
    std::vector<net::TestServer::StringPair> replacement_text;
    replacement_text.push_back(
        make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
    return net::TestServer::GetFilePathWithReplacements(
        original_file_path, replacement_text, replacement_path);
  }
};

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       SwapProcessWithRelNoreferrerAndTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server_(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server_.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server_.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer + target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);
  // Wait for the cross-site transition to finish.
  ui_test_utils::WaitForLoadStop(
      &(browser()->GetSelectedTabContents()->controller()));

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
  EXPECT_EQ(L"Title Of Awesomeness",
      browser()->GetSelectedTabContents()->GetTitle());

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server_(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server_.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server_.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);
  // Wait for the cross-site transition to finish.
  ui_test_utils::WaitForLoadStop(
      &(browser()->GetSelectedTabContents()->controller()));

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
  EXPECT_EQ(L"Title Of Awesomeness",
      browser()->GetSelectedTabContents()->GetTitle());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyRelNoreferrer) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server_(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server_.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server_.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);
  // Wait for the cross-site transition to finish.
  ui_test_utils::WaitForLoadStop(
      &(browser()->GetSelectedTabContents()->controller()));

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ(L"Title Of Awesomeness",
      browser()->GetSelectedTabContents()->GetTitle());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}

// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
#defne MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload
#endif  // defined(OS_WIN)

// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       MAYBE_ChromeURLAfterDownload) {
  GURL downloads_url("chrome://downloads");
  GURL extensions_url("chrome://extensions");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  ui_test_utils::NavigateToURL(browser(), zip_url);
  ui_test_utils::WaitForDownloadCount(
      browser()->profile()->GetDownloadManager(), 1);
  ui_test_utils::NavigateToURL(browser(), extensions_url);

  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool domui_responded = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.domAutomationController.send(window.domui_responded_);",
      &domui_responded));
  EXPECT_TRUE(domui_responded);
}

class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
        Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  // NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::BROWSER_CLOSED:
        MessageLoopForUI::current()->Quit();
        break;
    }
  }

 private:
  NotificationRegistrar registrar_;
};

// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DISABLED_BrowserCloseAfterDownload) {
  GURL downloads_url("chrome://downloads");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  ASSERT_TRUE(file_util::PathExists(zip_download));
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool result = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.onunload = function() { var do_nothing = 0; }; "
      L"window.domAutomationController.send(true);",
      &result));
  EXPECT_TRUE(result);
  ui_test_utils::NavigateToURL(browser(), zip_url);

  ui_test_utils::WaitForDownloadCount(
    browser()->profile()->GetDownloadManager(), 1);

  browser()->CloseWindow();
  BrowserClosedObserver wait_for_close(browser());
}
<commit_msg>Disable RenderViewHostManagerTest.DontSwapProcessWithOnlyTargetBlank<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/ref_counted.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

class RenderViewHostManagerTest : public InProcessBrowserTest {
 public:
  RenderViewHostManagerTest() {
    EnableDOMAutomation();
  }

  static bool GetFilePathWithHostAndPortReplacement(
      const std::string& original_file_path,
      const net::HostPortPair& host_port_pair,
      std::string* replacement_path) {
    std::vector<net::TestServer::StringPair> replacement_text;
    replacement_text.push_back(
        make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
    return net::TestServer::GetFilePathWithReplacements(
        original_file_path, replacement_text, replacement_path);
  }
};

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       SwapProcessWithRelNoreferrerAndTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server_(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server_.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server_.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer + target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);
  // Wait for the cross-site transition to finish.
  ui_test_utils::WaitForLoadStop(
      &(browser()->GetSelectedTabContents()->controller()));

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
  EXPECT_EQ(L"Title Of Awesomeness",
      browser()->GetSelectedTabContents()->GetTitle());

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
// Disabled, http://crbug.com/67532.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DISABLED_DontSwapProcessWithOnlyTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server_(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server_.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server_.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);
  // Wait for the cross-site transition to finish.
  ui_test_utils::WaitForLoadStop(
      &(browser()->GetSelectedTabContents()->controller()));

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
  EXPECT_EQ(L"Title Of Awesomeness",
      browser()->GetSelectedTabContents()->GetTitle());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyRelNoreferrer) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server_(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server_.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server_.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);
  // Wait for the cross-site transition to finish.
  ui_test_utils::WaitForLoadStop(
      &(browser()->GetSelectedTabContents()->controller()));

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ(L"Title Of Awesomeness",
      browser()->GetSelectedTabContents()->GetTitle());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}

// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
#defne MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload
#endif  // defined(OS_WIN)

// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       MAYBE_ChromeURLAfterDownload) {
  GURL downloads_url("chrome://downloads");
  GURL extensions_url("chrome://extensions");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  ui_test_utils::NavigateToURL(browser(), zip_url);
  ui_test_utils::WaitForDownloadCount(
      browser()->profile()->GetDownloadManager(), 1);
  ui_test_utils::NavigateToURL(browser(), extensions_url);

  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool domui_responded = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.domAutomationController.send(window.domui_responded_);",
      &domui_responded));
  EXPECT_TRUE(domui_responded);
}

class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
        Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  // NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::BROWSER_CLOSED:
        MessageLoopForUI::current()->Quit();
        break;
    }
  }

 private:
  NotificationRegistrar registrar_;
};

// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DISABLED_BrowserCloseAfterDownload) {
  GURL downloads_url("chrome://downloads");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  ASSERT_TRUE(file_util::PathExists(zip_download));
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool result = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.onunload = function() { var do_nothing = 0; }; "
      L"window.domAutomationController.send(true);",
      &result));
  EXPECT_TRUE(result);
  ui_test_utils::NavigateToURL(browser(), zip_url);

  ui_test_utils::WaitForDownloadCount(
    browser()->profile()->GetDownloadManager(), 1);

  browser()->CloseWindow();
  BrowserClosedObserver wait_for_close(browser());
}
<|endoftext|>


<commit_before>/*
Resembla
https://github.com/tuem/resembla

Copyright 2017 Takashi Uemura

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "flag_feature_aggregator.hpp"

#include <algorithm>
#include <iostream>

namespace resembla {

Feature::real_type FlagFeatureAggregatorImpl::operator()(Feature::real_type a, Feature::real_type b) const
{
    auto c = (std::abs(a) + std::abs(b) - 3.0 * std::abs(a - b)) / 2.0;
#ifdef DEBUG
    std::cerr << "flag-type feature: a=" << a << ", b=" << b << ", c=" << c << std::endl;
#endif
    return std::min(std::max(c, -1.0), 1.0);
}

}
<commit_msg>include header<commit_after>/*
Resembla
https://github.com/tuem/resembla

Copyright 2017 Takashi Uemura

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "flag_feature_aggregator.hpp"

#include <cmath>
#include <algorithm>

#ifdef DEBUG
#include <iostream>
#endif

namespace resembla {

Feature::real_type FlagFeatureAggregatorImpl::operator()(Feature::real_type a, Feature::real_type b) const
{
    auto c = (std::abs(a) + std::abs(b) - 3.0 * std::abs(a - b)) / 2.0;
#ifdef DEBUG
    std::cerr << "flag-type feature: a=" << a << ", b=" << b << ", c=" << c << std::endl;
#endif
    return std::min(std::max(c, -1.0), 1.0);
}

}
<|endoftext|>


<commit_before>/*
 Flexisip, a flexible SIP proxy server with media capabilities.
 Copyright (C) 2012  Belledonne Communications SARL.

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "agent.hh"
#include "event.hh"
#include "transaction.hh"
#include "common.hh"
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_tagarg.h>

using namespace ::std;

MsgSip::MsgSip(msg_t *msg, sip_t *sip) {
	LOGD("New MsgSip %p", this);
	mMsg = msg_copy(msg);
	mSip = sip_object(mMsg);
	mHome = msg_home(mMsg);
}

MsgSip::MsgSip(const MsgSip &msgSip) {
	LOGD("New MsgSip %p", this);
	mMsg = msg_copy(msgSip.mMsg);
	mSip = sip_object(mMsg);
	mHome = msg_home(mMsg);
}

void MsgSip::log(const char *fmt, ...) {
	if (IS_LOGD) {
		size_t msg_size;
		char *header = NULL;
		char *buf = NULL;
		if (fmt) {
			va_list args;
			va_start(args, fmt);
			header = su_vsprintf(mHome, fmt, args);
			va_end(args);
		}
		buf = msg_as_string(mHome, mMsg, NULL, 0, &msg_size);
		LOGD("%s%s%s", (header) ? header : "", (header) ? "\n" : "", buf);
	}
}

MsgSip::~MsgSip() {
	LOGD("Destroy MsgSip %p", this);
	msg_destroy(mMsg);
}

SipEvent::SipEvent(const shared_ptr<MsgSip> msgSip) :
		mCurrModule(NULL), mMsgSip(msgSip), mState(STARTED) {
	LOGD("New SipEvent %p", this);
}

SipEvent::SipEvent(const SipEvent &sipEvent) :
		mCurrModule(sipEvent.mCurrModule), mMsgSip(sipEvent.mMsgSip), mIncomingAgent(sipEvent.mIncomingAgent), mOutgoingAgent(sipEvent.mOutgoingAgent), mState(sipEvent.mState) {
	LOGD("New SipEvent %p", this);
}

SipEvent::~SipEvent() {
	LOGD("Destroy SipEvent %p", this);
}

void SipEvent::terminateProcessing() {
	LOGD("Terminate SipEvent %p", this);
	if (mState == STARTED || mState == SUSPENDED) {
		mState = TERMINATED;
	} else {
		LOGA("Can't terminateProcessing: wrong state");
	}
}

void SipEvent::suspendProcessing() {
	LOGD("Suspend SipEvent %p", this);
	if (mState == STARTED) {
		mState = SUSPENDED;
	} else {
		LOGA("Can't suspendProcessing: wrong state");
	}
}

void SipEvent::restartProcessing() {
	LOGD("Restart SipEvent %p", this);
	if (mState == SUSPENDED) {
		mState = STARTED;
	} else {
		LOGA("Can't restartProcessing: wrong state");
	}
}

shared_ptr<IncomingTransaction> SipEvent::createIncomingTransaction() {
	shared_ptr<IncomingTransaction> transaction = dynamic_pointer_cast<IncomingTransaction>(mIncomingAgent);
	if (transaction == NULL) {
		transaction = shared_ptr<IncomingTransaction>(new IncomingTransaction(mIncomingAgent->getAgent()));
		transaction->handle(mMsgSip);
		mIncomingAgent = transaction;
	}
	return transaction;
}

shared_ptr<OutgoingTransaction> SipEvent::createOutgoingTransaction() {
	shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(mOutgoingAgent);
	if (transaction == NULL) {
		transaction = shared_ptr<OutgoingTransaction>(new OutgoingTransaction(mOutgoingAgent->getAgent()));
		mOutgoingAgent = transaction;
	}
	return transaction;
}

RequestSipEvent::RequestSipEvent(const shared_ptr<IncomingAgent> &incomingAgent, const shared_ptr<MsgSip> &msgSip) :
		SipEvent(msgSip) {
	mIncomingAgent = incomingAgent;
	mOutgoingAgent = incomingAgent->getAgent()->shared_from_this();
}

RequestSipEvent::RequestSipEvent(const shared_ptr<SipEvent> &sipEvent) :
		SipEvent(*sipEvent) {
}

void RequestSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
	if (mOutgoingAgent != NULL) {
		if (IS_LOGD) {
			msg->log("Sending Request SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
		}
		ta_list ta;
		ta_start(ta, tag, value);
		mOutgoingAgent->send(msg, u, ta_tags(ta));
		ta_end(ta);
	} else {
		LOGD("The Request SIP message is not send");
	}
	terminateProcessing();
}

void RequestSipEvent::send(const shared_ptr<MsgSip> &msg) {
	if (mOutgoingAgent != NULL) {
		if (IS_LOGD) {
			msg->log("Sending Request SIP message:");
		}
		mOutgoingAgent->send(msg);
	} else {
		LOGD("The Request SIP message is not send");
	}
	terminateProcessing();
}

void RequestSipEvent::reply(const shared_ptr<MsgSip> &msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
	if (mIncomingAgent != NULL) {
		if (IS_LOGD) {
			LOGD("Replying Request SIP message: %i %s\n\n", status, phrase);
		}
		ta_list ta;
		ta_start(ta, tag, value);
		mIncomingAgent->reply(msg, status, phrase, ta_tags(ta));
		ta_end(ta);
	} else {
		LOGD("The Request SIP message is not reply");
	}
	terminateProcessing();
}

void RequestSipEvent::setIncomingAgent(const shared_ptr<IncomingAgent> &agent) {
	LOGA("Can't change incoming agent in request sip event");
}

RequestSipEvent::~RequestSipEvent() {
}

ResponseSipEvent::ResponseSipEvent(const shared_ptr<OutgoingAgent> &outgoingAgent, const shared_ptr<MsgSip> &msgSip) :
		SipEvent(msgSip) {
	mOutgoingAgent = outgoingAgent;
	mIncomingAgent = outgoingAgent->getAgent()->shared_from_this();
}

ResponseSipEvent::ResponseSipEvent(const shared_ptr<SipEvent> &sipEvent) :
		SipEvent(*sipEvent) {
}

void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
	if (mIncomingAgent != NULL) {
		if (IS_LOGD) {
			msg->log("Sending Response SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
		}
		ta_list ta;
		ta_start(ta, tag, value);
		mIncomingAgent->send(msg, u, ta_tags(ta));
		ta_end(ta);
	} else {
		LOGD("The Response SIP message is not send");
	}
	terminateProcessing();
}

void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg) {
	if (mIncomingAgent != NULL) {
		if (IS_LOGD) {
			msg->log("Sending Response SIP message:");
		}
		mIncomingAgent->send(msg);
	} else {
		LOGD("The Response SIP message is not send");
	}
	terminateProcessing();
}

void ResponseSipEvent::reply(const shared_ptr<MsgSip> &msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
	LOGA("Can't reply to an response sip event");
}

void ResponseSipEvent::setOutgoingAgent(const shared_ptr<OutgoingAgent> &agent) {
	LOGA("Can't change outgoing agent in response sip event");
}

ResponseSipEvent::~ResponseSipEvent() {

}
<commit_msg>cleanup traces<commit_after>/*
 Flexisip, a flexible SIP proxy server with media capabilities.
 Copyright (C) 2012  Belledonne Communications SARL.

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "agent.hh"
#include "event.hh"
#include "transaction.hh"
#include "common.hh"
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_tagarg.h>

using namespace ::std;

MsgSip::MsgSip(msg_t *msg, sip_t *sip) {
	//LOGD("New MsgSip %p", this);
	mMsg = msg_copy(msg);
	mSip = sip_object(mMsg);
	mHome = msg_home(mMsg);
}

MsgSip::MsgSip(const MsgSip &msgSip) {
	//LOGD("New MsgSip %p", this);
	mMsg = msg_copy(msgSip.mMsg);
	mSip = sip_object(mMsg);
	mHome = msg_home(mMsg);
}

void MsgSip::log(const char *fmt, ...) {
	if (IS_LOGD) {
		size_t msg_size;
		char *header = NULL;
		char *buf = NULL;
		if (fmt) {
			va_list args;
			va_start(args, fmt);
			header = su_vsprintf(mHome, fmt, args);
			va_end(args);
		}
		buf = msg_as_string(mHome, mMsg, NULL, 0, &msg_size);
		LOGD("%s%s%s", (header) ? header : "", (header) ? "\n" : "", buf);
	}
}

MsgSip::~MsgSip() {
	//LOGD("Destroy MsgSip %p", this);
	msg_destroy(mMsg);
}

SipEvent::SipEvent(const shared_ptr<MsgSip> msgSip) :
		mCurrModule(NULL), mMsgSip(msgSip), mState(STARTED) {
	LOGD("New SipEvent %p", this);
}

SipEvent::SipEvent(const SipEvent &sipEvent) :
		mCurrModule(sipEvent.mCurrModule), mMsgSip(sipEvent.mMsgSip), mIncomingAgent(sipEvent.mIncomingAgent), mOutgoingAgent(sipEvent.mOutgoingAgent), mState(sipEvent.mState) {
	LOGD("New SipEvent %p", this);
}

SipEvent::~SipEvent() {
	//LOGD("Destroy SipEvent %p", this);
}

void SipEvent::terminateProcessing() {
	LOGD("Terminate SipEvent %p", this);
	if (mState == STARTED || mState == SUSPENDED) {
		mState = TERMINATED;
	} else {
		LOGA("Can't terminateProcessing: wrong state");
	}
}

void SipEvent::suspendProcessing() {
	LOGD("Suspend SipEvent %p", this);
	if (mState == STARTED) {
		mState = SUSPENDED;
	} else {
		LOGA("Can't suspendProcessing: wrong state");
	}
}

void SipEvent::restartProcessing() {
	LOGD("Restart SipEvent %p", this);
	if (mState == SUSPENDED) {
		mState = STARTED;
	} else {
		LOGA("Can't restartProcessing: wrong state");
	}
}

shared_ptr<IncomingTransaction> SipEvent::createIncomingTransaction() {
	shared_ptr<IncomingTransaction> transaction = dynamic_pointer_cast<IncomingTransaction>(mIncomingAgent);
	if (transaction == NULL) {
		transaction = shared_ptr<IncomingTransaction>(new IncomingTransaction(mIncomingAgent->getAgent()));
		transaction->handle(mMsgSip);
		mIncomingAgent = transaction;
	}
	return transaction;
}

shared_ptr<OutgoingTransaction> SipEvent::createOutgoingTransaction() {
	shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(mOutgoingAgent);
	if (transaction == NULL) {
		transaction = shared_ptr<OutgoingTransaction>(new OutgoingTransaction(mOutgoingAgent->getAgent()));
		mOutgoingAgent = transaction;
	}
	return transaction;
}

RequestSipEvent::RequestSipEvent(const shared_ptr<IncomingAgent> &incomingAgent, const shared_ptr<MsgSip> &msgSip) :
		SipEvent(msgSip) {
	mIncomingAgent = incomingAgent;
	mOutgoingAgent = incomingAgent->getAgent()->shared_from_this();
}

RequestSipEvent::RequestSipEvent(const shared_ptr<SipEvent> &sipEvent) :
		SipEvent(*sipEvent) {
}

void RequestSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
	if (mOutgoingAgent != NULL) {
		if (IS_LOGD) {
			msg->log("Sending Request SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
		}
		ta_list ta;
		ta_start(ta, tag, value);
		mOutgoingAgent->send(msg, u, ta_tags(ta));
		ta_end(ta);
	} else {
		LOGD("The Request SIP message is not send");
	}
	terminateProcessing();
}

void RequestSipEvent::send(const shared_ptr<MsgSip> &msg) {
	if (mOutgoingAgent != NULL) {
		if (IS_LOGD) {
			msg->log("Sending Request SIP message:");
		}
		mOutgoingAgent->send(msg);
	} else {
		LOGD("The Request SIP message is not send");
	}
	terminateProcessing();
}

void RequestSipEvent::reply(const shared_ptr<MsgSip> &msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
	if (mIncomingAgent != NULL) {
		if (IS_LOGD) {
			LOGD("Replying Request SIP message: %i %s\n\n", status, phrase);
		}
		ta_list ta;
		ta_start(ta, tag, value);
		mIncomingAgent->reply(msg, status, phrase, ta_tags(ta));
		ta_end(ta);
	} else {
		LOGD("The Request SIP message is not reply");
	}
	terminateProcessing();
}

void RequestSipEvent::setIncomingAgent(const shared_ptr<IncomingAgent> &agent) {
	LOGA("Can't change incoming agent in request sip event");
}

RequestSipEvent::~RequestSipEvent() {
}

ResponseSipEvent::ResponseSipEvent(const shared_ptr<OutgoingAgent> &outgoingAgent, const shared_ptr<MsgSip> &msgSip) :
		SipEvent(msgSip) {
	mOutgoingAgent = outgoingAgent;
	mIncomingAgent = outgoingAgent->getAgent()->shared_from_this();
}

ResponseSipEvent::ResponseSipEvent(const shared_ptr<SipEvent> &sipEvent) :
		SipEvent(*sipEvent) {
}

void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg, url_string_t const *u, tag_type_t tag, tag_value_t value, ...) {
	if (mIncomingAgent != NULL) {
		if (IS_LOGD) {
			msg->log("Sending Response SIP message to=%s:", u ? url_as_string(msg->getHome(), (url_t const *) u) : NULL);
		}
		ta_list ta;
		ta_start(ta, tag, value);
		mIncomingAgent->send(msg, u, ta_tags(ta));
		ta_end(ta);
	} else {
		LOGD("The Response SIP message is not send");
	}
	terminateProcessing();
}

void ResponseSipEvent::send(const shared_ptr<MsgSip> &msg) {
	if (mIncomingAgent != NULL) {
		if (IS_LOGD) {
			msg->log("Sending Response SIP message:");
		}
		mIncomingAgent->send(msg);
	} else {
		LOGD("The Response SIP message is not send");
	}
	terminateProcessing();
}

void ResponseSipEvent::reply(const shared_ptr<MsgSip> &msg, int status, char const *phrase, tag_type_t tag, tag_value_t value, ...) {
	LOGA("Can't reply to an response sip event");
}

void ResponseSipEvent::setOutgoingAgent(const shared_ptr<OutgoingAgent> &agent) {
	LOGA("Can't change outgoing agent in response sip event");
}

ResponseSipEvent::~ResponseSipEvent() {

}
<|endoftext|>


<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: bulkDataNTStream.cpp,v 1.21 2011/09/28 16:43:42 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram  2011-04-19  created
*/
#include "bulkDataNTStream.h"
#include <iostream>
using namespace ACS_BD_Errors;
using namespace ACSErrTypeCommon;
using namespace ACS_DDS_Errors;

using namespace AcsBulkdata;

BulkDataNTStream::BulkDataNTStream(const char* name, const StreamConfiguration &cfg) :
	streamName_m(name), configuration_m(cfg), factory_m(0), participant_m(0)
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	try
	{
		createDDSFactory();
		createDDSParticipant(); //should be somewhere else in initialize or createStream
	}catch(const ACSErr::ACSbaseExImpl &e)
	{
		if (factory_m!=0)
			DDS::DomainParticipantFactory::finalize_instance();
		StreamCreateProblemExImpl ex (e, __FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setStreamName(name);
		throw ex;
	}//try-catch
}//BulkDataNTStream

BulkDataNTStream::~BulkDataNTStream()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	destroyDDSParticipant();
	DDS::DomainParticipantFactory::finalize_instance();
}//~BulkDataNTStream

void BulkDataNTStream::createDDSFactory()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	DDS::DomainParticipantFactoryQos factory_qos;

	factory_m = DDS::DomainParticipantFactory::get_instance();

	// needed by RTI only
	ret = factory_m->get_qos(factory_qos);
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("factory_m->get_qos");
		throw ex;
	}//if
	factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;

	// if both values are true (default) we prevent that default values are taken from default places
	factory_qos.profile.ignore_user_profile = configuration_m.ignoreUserProfileQoS;
	factory_qos.profile.ignore_environment_profile = configuration_m.ignoreEnvironmentProfileQoS;

	if (configuration_m.stringProfileQoS.length()>0)
	{
		factory_qos.profile.string_profile.ensure_length(1,1);
		factory_qos.profile.string_profile[0] = DDS_String_dup(configuration_m.stringProfileQoS.c_str());
	}//if

	if (configuration_m.urlProfileQoS.length()>0)
	{
		factory_qos.profile.url_profile.ensure_length(1,1);
		factory_qos.profile.url_profile[0] = DDS_String_dup(configuration_m.urlProfileQoS.c_str());
	}//if
	ret = factory_m->set_qos(factory_qos);
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("factory_m->set_qos");
		throw ex;
	}//if

	//RTI logging
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
			NDDS_CONFIG_LOG_CATEGORY_API,
			(NDDS_Config_LogVerbosity)(configuration_m.DDSLogVerbosity));
}//createDDSFactory

void BulkDataNTStream::createDDSParticipant()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	DDS::DomainParticipantQos participant_qos;
	int domainID=0; //TBD: where to get domain ID

	if (factory_m==NULL)
	{
		NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setVariable("factory_m");
		throw ex;
	}

	if (participant_m!=NULL)
	{
		printf("participant already created\n");
		return;
	}

	ret = factory_m->get_participant_qos_from_profile(participant_qos, configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str());
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("get_participant_qos_from_profile");
		throw ex;
	}//if

	participant_m =factory_m->create_participant(domainID, participant_qos, NULL, DDS::STATUS_MASK_NONE );
	if (participant_m==NULL)
	{
		DDSParticipantCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDomainID(domainID);
		throw ex;
	}

	ret = participant_m->enable();
}//createDDSParticipant

void BulkDataNTStream::destroyDDSParticipant()
{
	DDS::ReturnCode_t ret;
	AUTO_TRACE(__PRETTY_FUNCTION__);
	ret = factory_m->delete_participant(participant_m);
	if (ret != DDS_RETCODE_OK)
	{
		DDSParticipantDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.log();
	}//if
}//destroyDDSParticipant
<commit_msg>added error handling for enable participant<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: bulkDataNTStream.cpp,v 1.22 2011/11/25 09:07:13 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram  2011-04-19  created
*/
#include "bulkDataNTStream.h"
#include <iostream>
using namespace ACS_BD_Errors;
using namespace ACSErrTypeCommon;
using namespace ACS_DDS_Errors;

using namespace AcsBulkdata;

BulkDataNTStream::BulkDataNTStream(const char* name, const StreamConfiguration &cfg) :
	streamName_m(name), configuration_m(cfg), factory_m(0), participant_m(0)
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	try
	{
		createDDSFactory();
		createDDSParticipant(); //should be somewhere else in initialize or createStream
	}catch(const ACSErr::ACSbaseExImpl &e)
	{
		if (factory_m!=0)
			DDS::DomainParticipantFactory::finalize_instance();
		StreamCreateProblemExImpl ex (e, __FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setStreamName(name);
		throw ex;
	}//try-catch
}//BulkDataNTStream

BulkDataNTStream::~BulkDataNTStream()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);

	destroyDDSParticipant();
	DDS::DomainParticipantFactory::finalize_instance();
}//~BulkDataNTStream

void BulkDataNTStream::createDDSFactory()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	DDS::DomainParticipantFactoryQos factory_qos;

	factory_m = DDS::DomainParticipantFactory::get_instance();

	// needed by RTI only
	ret = factory_m->get_qos(factory_qos);
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("factory_m->get_qos");
		throw ex;
	}//if
	factory_qos.entity_factory.autoenable_created_entities = DDS_BOOLEAN_FALSE;

	// if both values are true (default) we prevent that default values are taken from default places
	factory_qos.profile.ignore_user_profile = configuration_m.ignoreUserProfileQoS;
	factory_qos.profile.ignore_environment_profile = configuration_m.ignoreEnvironmentProfileQoS;

	if (configuration_m.stringProfileQoS.length()>0)
	{
		factory_qos.profile.string_profile.ensure_length(1,1);
		factory_qos.profile.string_profile[0] = DDS_String_dup(configuration_m.stringProfileQoS.c_str());
	}//if

	if (configuration_m.urlProfileQoS.length()>0)
	{
		factory_qos.profile.url_profile.ensure_length(1,1);
		factory_qos.profile.url_profile[0] = DDS_String_dup(configuration_m.urlProfileQoS.c_str());
	}//if
	ret = factory_m->set_qos(factory_qos);
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("factory_m->set_qos");
		throw ex;
	}//if

	//RTI logging
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
			NDDS_CONFIG_LOG_CATEGORY_API,
			(NDDS_Config_LogVerbosity)(configuration_m.DDSLogVerbosity));
}//createDDSFactory

void BulkDataNTStream::createDDSParticipant()
{
	AUTO_TRACE(__PRETTY_FUNCTION__);
	DDS::ReturnCode_t ret;
	DDS::DomainParticipantQos participant_qos;
	int domainID=0; //TBD: where to get domain ID

	if (factory_m==NULL)
	{
		NullPointerExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setVariable("factory_m");
		throw ex;
	}

	if (participant_m!=NULL)
	{
		printf("participant already created\n");
		return;
	}

	ret = factory_m->get_participant_qos_from_profile(participant_qos, configuration_m.libraryQos.c_str(), configuration_m.profileQos.c_str());
	if (ret!=DDS::RETCODE_OK)
	{
		DDSQoSSetProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDDSTypeCode(ret);
		ex.setQoS("get_participant_qos_from_profile");
		throw ex;
	}//if

	participant_m =factory_m->create_participant(domainID, participant_qos, NULL, DDS::STATUS_MASK_NONE );
	if (participant_m==NULL)
	{
		DDSParticipantCreateProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.setDomainID(domainID);
		throw ex;
	}

	ret = participant_m->enable();
	if (ret!=DDS::RETCODE_OK)
	  {
	    DDSParticipantEnableProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
	    ex.setDDSTypeCode(ret);
	    ex.setDomainID(domainID);
	    throw ex;
	  }//if
}//createDDSParticipant

void BulkDataNTStream::destroyDDSParticipant()
{
	DDS::ReturnCode_t ret;
	AUTO_TRACE(__PRETTY_FUNCTION__);
	ret = factory_m->delete_participant(participant_m);
	if (ret != DDS_RETCODE_OK)
	{
		DDSParticipantDestroyProblemExImpl ex(__FILE__, __LINE__, __PRETTY_FUNCTION__);
		ex.log();
	}//if
}//destroyDDSParticipant
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>

using namespace std;

//___ERROR LIST___
//test exit after commands
//test semi-colons before/after commands
//Prompt multi-prints when space-separated garbage is entered
//Test with whitespace before/inbetween/after commands
//Test touch with large, small, and symbol commands

int main(int argc, char*argv[]){
    bool isRunning = true;
    while(isRunning){
        cout << "$"; //Prints the Prompt
	string input;
	getline(cin, input);
	if(input == "exit"){ //Exit Check
	    cout << "Exiting rshell..." << endl;
	    return 0;
	}
	int cnt = 0;//where cnt used to be - FIXME
	char * tokInput = new char[input.size() + 1];
	copy(input.begin(), input.end(), tokInput);//tokInput now = input
	tokInput[input.size()] = '\0'; //Null terminates array
	char* token = strtok(tokInput, "-;|&\""); //parses rawInput

	while(token != NULL){//Tokenization
	    cout << "token: " << token << endl;//output - FIXME
	    /*if(*token == '#'){
		strcpy(argv[cnt], "\0"); //null terminates argv
		token = NULL;
	    }*/
	    argv[cnt] = token;//places tokens into argv
	   // strcat(argv[cnt], "\0");//adds null char to argv
	    token = strtok(NULL, "-;|&\" "); //looks for connectors
	    cnt++; //increment count
	}
	//strcat(argv[cnt], "\0");//Null terminates argv[]
	for(int i = 0; i < cnt; i++){ //prints all values of argv[] - FIXME
	    cout << "argv[" << i << "]: " << argv[i] << endl;
	}

	int pid = fork();//forks the process
        if(pid == 0){ //child process
	   //if(execvp(argv[0], &argv[0]) == -1){ - Old
	    if(execvp(argv[0], argv) == -1){
	        perror("execvp failure");
	    }
	    exit(1);
	}else{ //parent
	    if(-1 == wait(NULL)){
	        perror("wait() failure");
	    }
        }
    }//end isRunning loop
    return 0;
}
<commit_msg>New exec.cpp, now tokenizes properly and handles comments<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstring>

using namespace std;

int main(int argc, char*argv[]){
    bool isOn = true; //Keeps track of whether rshell is still running
    string usrInput;
    while(isOn){
        cout << "$ "; //Prints prompt
	getline(cin, usrInput);

	char* inputCpy = new char[usrInput.length() + 1]; //pointer for input string
	strcpy(inputCpy, usrInput.c_str()); //token now holds c-string copy of input

	char* token = strtok(inputCpy, " ;"); //removes semicolons
	unsigned cnt = 0; //counter for slots in argv[]
	while(token != NULL){
	    cout << token << endl;//Fixme - remove later
	    if(*token == '#'){ //Handles comments
		token = NULL;
	    }else{ //Default scenario
	        argv[cnt] = token;
	        token = strtok(NULL, " ;");
	        cnt++;
	    }
	}
	for(unsigned i = 0; i < cnt; i++){
	    cout << "Argv[" << i << "]: " << argv[i] << endl; //Fixme - remove later
	}

    }
    return 0;
}

//---------------------OLD CODE BELOW THIS LINE---------------------

//___ERROR LIST___
//test exit after commands
//test semi-colons before/after commands
//Prompt multi-prints when space-separated garbage is entered
//Test with whitespace before/inbetween/after commands
//Test touch with large, small, and symbol commands
//Must work with &&'s and ||'s as connectors

/*

int main(int argc, char*argv[]){
    bool isRunning = true;
    while(isRunning){
        cout << "$"; //Prints the Prompt
	string input;
	getline(cin, input);
	if(input == "exit"){ //Exit Check
	    cout << "Exiting rshell..." << endl;
	    return 0;
	}
	int cnt = 0;
	char * tokInput = new char[input.size() + 1];
	copy(input.begin(), input.end(), tokInput);//tokInput now = input
	tokInput[input.size()] = '\0'; //Null terminates array
	char* token = strtok(tokInput, ";"); //parses rawInput
	char* arr[] = strtok(tokInput, ";");

	while(token != NULL){//Tokenization
	    cout << "token: " << token << endl;//output - FIXME
	    //if(*token == '#'){
		//strcpy(argv[cnt], "\0"); //null terminates argv
		//token = NULL;
	    }
	    argv[cnt] = token;//places tokenized strings into argv
	    strcat(argv[cnt], "\0");//adds null char to strings in argv
	    token = strtok(NULL, " "); //looks for connectors
	    cnt++; //increment count
	}
	//strcat(argv[cnt], "\0");//Null terminates argv[]
	for(int i = 0; i < cnt; i++){ //prints all values of argv[] - FIXME
	    cout << "argv[" << i << "]: " << argv[i] << endl;
	}

	int pid = fork();//forks the process
        if(pid == 0){ //child process
	   //if(execvp(argv[0], &argv[0]) == -1){ - Old
	    if(execvp(argv[0], argv) == -1){
	        perror("execvp failure");
	    }
	    exit(1);
	}else{ //parent
	    if(-1 == wait(NULL)){
	        perror("wait() failure");
	    }
        }
    }//end isRunning loop
    return 0;
}
*/
<|endoftext|>


<commit_before>// BriocheBot
// The MIT License(MIT)
//
// Copyright(c) 2015 Abricot Soinou <abricot.soinou@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.

///////////////////////////////////////////////
//
// Current mode: Database migration
// Will migrate everything from the old players
// to the new viewers-models
//
///////////////////////////////////////////////

#include "models/viewers.h"
#include "models/viewer.h"
#include "models/streamer.h"
#include "models/moderator.h"
#include "utils/redis.h"
#include "utils/utils.h"

// Extra program, used to do some extra things
int main()
{
    the_viewers.load();

    // Connect to redis
    Redis::Connection connection("127.0.0.1", 6379);

    // Json reader we'll use
    Json::Reader reader;

    printf("Getting all keys...\n\n");

    // Get all the keys we have in redis
    Redis::Reply reply = connection.execute("KEYS *");

    printf("Got all keys, scanning keys...\n");

    // If we got an array
    if (reply.type == Redis::Reply::Array)
    {
        int count = the_viewers.max_id();

        // For each key
        for (auto i = reply.elements.begin(); i != reply.elements.end(); i++)
        {
            // Get this element
            Redis::Reply element = *i;

            printf("  Scanning key \"%s\"...\n", element.string.c_str());

            // Get the element value
            int value = atoi(element.string.c_str());

            // We got 0
            if (value == 0)
                // Not valid
                printf("    Key is not valid, skipping\n\n");
            // We got a number
            else
            {
                // Valid
                printf("    Key is a streamer, getting data...\n", value);

                // Get the streamer
                Redis::Reply streamer = connection.execute(Utils::string_format("GET %d", value));

                // Reply is a string
                if (streamer.type == Redis::Reply::String)
                {
                    printf("      Got data, creating streamer...\n");

                    // Json we'll need
                    Json::Value json;

                    // Parse the json
                    reader.parse(streamer.string, json);

                    // If the streamer already exists, skip
                    if (the_viewers.exists(json["twitch_username"].asString()))
                        printf("      Streamer already exists, skipping\n\n");
                    // If the streamer doesn't already exists
                    else
                    {
                        // Create a new streamer
                        Streamer* new_streamer = nullptr;

                        // If this streamer was an admin
                        if (json["admin"].asBool())
                        {
                            // Create a new moderator
                            Moderator* moderator = new Moderator();
                            // Set his privileges
                            moderator->set_privileges(1);
                            // Pass it to our viewer
                            new_streamer = moderator;
                        }
                        // Else
                        else
                            // Just create a new streamer
                            new_streamer = new Streamer();

                        // Set streamer data
                        new_streamer->set_id(count++);
                        new_streamer->set_twitch_username(json["twitch_username"].asString());
                        new_streamer->set_osu_username(json["osu_username"].asString());
                        new_streamer->set_osu_skin_link(json["osu_skin"].asString());

                        printf("      Streamer created, adding him...\n");

                        // Insert the streamer
                        new_streamer->insert();

                        printf("      Streamer added!\n\n");
                    }
                }
            }
        }
    }

    return 0;
}
<commit_msg>Little mistake<commit_after>// BriocheBot
// The MIT License(MIT)
//
// Copyright(c) 2015 Abricot Soinou <abricot.soinou@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.

///////////////////////////////////////////////
//
// Current mode: Database migration
// Will migrate everything from the old players
// to the new viewers-models
//
///////////////////////////////////////////////

#include "models/viewers.h"
#include "models/viewer.h"
#include "models/streamer.h"
#include "models/moderator.h"
#include "utils/redis.h"
#include "utils/utils.h"

// Extra program, used to do some extra things
int main()
{
    the_viewers.load();

    // Connect to redis
    Redis::Connection connection("127.0.0.1", 6379);

    // Json reader we'll use
    Json::Reader reader;

    printf("Getting all keys...\n\n");

    // Get all the keys we have in redis
    Redis::Reply reply = connection.execute("KEYS *");

    printf("Got all keys, scanning keys...\n");

    // If we got an array
    if (reply.type == Redis::Reply::Array)
    {
        int count = the_viewers.max_id();

        // For each key
        for (auto i = reply.elements.begin(); i != reply.elements.end(); i++)
        {
            // Get this element
            Redis::Reply element = *i;

            printf("  Scanning key \"%s\"...\n", element.string.c_str());

            // Get the element value
            int value = atoi(element.string.c_str());

            // We got 0
            if (value == 0)
                // Not valid
                printf("    Key is not valid, skipping\n\n");
            // We got a number
            else
            {
                // Valid
                printf("    Key is a streamer, getting data...\n");

                // Get the streamer
                Redis::Reply streamer = connection.execute(Utils::string_format("GET %d", value));

                // Reply is a string
                if (streamer.type == Redis::Reply::String)
                {
                    printf("      Got data, creating streamer...\n");

                    // Json we'll need
                    Json::Value json;

                    // Parse the json
                    reader.parse(streamer.string, json);

                    // If the streamer already exists, skip
                    if (the_viewers.exists(json["twitch_username"].asString()))
                        printf("      Streamer already exists, skipping\n\n");
                    // If the streamer doesn't already exists
                    else
                    {
                        // Create a new streamer
                        Streamer* new_streamer = nullptr;

                        // If this streamer was an admin
                        if (json["admin"].asBool())
                        {
                            // Create a new moderator
                            Moderator* moderator = new Moderator();
                            // Set his privileges
                            moderator->set_privileges(1);
                            // Pass it to our viewer
                            new_streamer = moderator;
                        }
                        // Else
                        else
                            // Just create a new streamer
                            new_streamer = new Streamer();

                        // Set streamer data
                        new_streamer->set_id(count++);
                        new_streamer->set_twitch_username(json["twitch_username"].asString());
                        new_streamer->set_osu_username(json["osu_username"].asString());
                        new_streamer->set_osu_skin_link(json["osu_skin"].asString());

                        printf("      Streamer created, adding him...\n");

                        // Insert the streamer
                        new_streamer->insert();

                        printf("      Streamer added!\n\n");
                    }
                }
            }
        }
    }

    return 0;
}
<|endoftext|>