text:
package fragment.web;

import java.io.IOException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Currency;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.JsonMappingException;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.handler.DispatcherServletWebRequest;

import web.WebTestsBaseWithMockConnectors;
import web.support.DispatcherTestServlet;
import web.support.MockSessionStatus;

import com.citrix.cpbm.access.proxy.CustomProxy;
import com.citrix.cpbm.core.workflow.service.BusinessTransactionService;
import com.citrix.cpbm.core.workflow.service.TaskService;
import com.citrix.cpbm.platform.admin.service.utils.ServiceInstanceConfiguration;
import com.citrix.cpbm.platform.bootstrap.service.BootstrapActivator;
import com.citrix.cpbm.platform.spi.AccountLifecycleHandler;
import com.citrix.cpbm.platform.spi.CloudConnector;
import com.citrix.cpbm.platform.spi.UserLifecycleHandler;
import com.citrix.cpbm.portal.forms.UserRegistration;
import com.citrix.cpbm.portal.fragment.controllers.RegistrationController;
import com.citrix.cpbm.portal.fragment.controllers.TasksController;
import com.vmops.event.EmailVerified;
import com.vmops.event.PortalEvent;
import com.vmops.event.TenantActivation;
import com.vmops.event.VerifyEmailRequest;
import com.vmops.internal.service.PaymentGatewayService;
import com.vmops.model.AccountType;
import com.vmops.model.Address;
import com.vmops.model.CampaignPromotion;
import com.vmops.model.CampaignPromotionsInChannels;
import com.vmops.model.Channel;
import com.vmops.model.Configuration;
import com.vmops.model.Country;
import com.vmops.model.ProductBundleRevision;
import com.vmops.model.PromotionSignup;
import com.vmops.model.PromotionToken;
import com.vmops.model.Service;
import com.vmops.model.Tenant;
import com.vmops.model.User;
import com.vmops.model.billing.PaymentTransaction;
import com.vmops.model.billing.PaymentTransaction.State;
import com.vmops.persistence.AccountTypeDAO;
import com.vmops.persistence.CampaignPromotionDAO;
import com.vmops.persistence.PromotionTokenDAO;
import com.vmops.portal.config.Configuration.Names;
import com.vmops.service.AuthorityService;
import com.vmops.service.ChannelService;
import com.vmops.service.ConfigurationService;
import com.vmops.service.exceptions.UserAuthorizationInvalidException;
import com.vmops.web.controllers.menu.Page;
import com.vmops.web.forms.CreditCardType;
import common.MockCloudInstance;

public class RegistrationControllerTest extends WebTestsBaseWithMockConnectors {

  private ModelMap map;

  private MockSessionStatus status;

  private MockHttpServletRequest request;

  private MockHttpSession session;

  @Autowired
  private ChannelService channelService2;

  @Autowired
  private RegistrationController controller;

  @JsonProperty
  private com.citrix.cpbm.access.Tenant tenant;

  @Autowired
  AccountTypeDAO accountTypeDAO;

  @Autowired
  private CampaignPromotionDAO cmpdao;

  @Autowired
  private PromotionTokenDAO tokendao;

  @Autowired
  private ConfigurationService configurationService;

  @Autowired
  private BusinessTransactionService businessTransactionService;

  @Autowired
  ChannelService channelservice;

  @Autowired
  CampaignPromotionDAO campaignpromotiondao;

  private BootstrapActivator bootstrapActivator = new BootstrapActivator();

  private static boolean isMockInstanceCreated = false;

  private PaymentGatewayService ossConnector = null;

  @Autowired
  private TasksController tasksController;

  @Autowired
  private AuthorityService authorityService;

  @Autowired
  private TaskService taskService;

  @Before
  public void init() throws Exception {
    map = new ModelMap();
    status = new MockSessionStatus();
    request = new MockHttpServletRequest();
    session = new MockHttpSession();
    request.setSession(session);
    prepareMock(true, bootstrapActivator);
    if (isMockInstanceCreated == false) {

      Service ossService = serviceDAO.find(7l);
      ossService.setEnabled(true);
      Service cloudService = serviceDAO.find(6l);
      connectorManagementService.getAllServiceInstances(cloudService);

      isMockInstanceCreated = true;
    }
    asRoot();
  }

  @Override
  protected void prepareMock(boolean adaptor, BootstrapActivator bootstrapActivator) {
    super.prepareMock(adaptor, bootstrapActivator);
    MockCloudInstance instance = getMockCloudInstance();
    CloudConnector connector = instance.getCloudConnector();
    ossConnector = EasyMock.createMock(PaymentGatewayService.class);
    mockAccountLifecycleHandler = EasyMock.createMock(AccountLifecycleHandler.class);
    mockUserLifecycleHandler = EasyMock.createMock(UserLifecycleHandler.class);
    EasyMock.expect(connector.getServiceInstanceUUID()).andReturn("12345-786").anyTimes();
    EasyMock.replay(connector);
    ServiceInstanceConfiguration sic2 = connector.getServiceInstanceConfiguration();
    EasyMock.reset(ossConnector);
    EasyMock.expect(ossConnector.getAccountLifeCycleHandler()).andReturn(mockAccountLifecycleHandler).anyTimes();
    EasyMock.expect(ossConnector.getUserLifeCycleHandler()).andReturn(mockUserLifecycleHandler).anyTimes();
    EasyMock.expect(sic2.getInstanceUUID()).andReturn("003fa8ee-fba3-467f-a517-ed806dae8a80").anyTimes();
    final Capture<BigDecimal> amount = new Capture<BigDecimal>();
    EasyMock.expect(ossConnector.authorize(EasyMock.anyObject(Tenant.class), EasyMock.capture(amount)))
        .andAnswer(new IAnswer<PaymentTransaction>() {

          @Override
          public PaymentTransaction answer() throws Throwable {
            return new PaymentTransaction(new Tenant(), 0, State.COMPLETED,
                com.vmops.model.billing.PaymentTransaction.Type.CAPTURE);
          }
        }).anyTimes();
    EasyMock.replay(ossConnector);
    EasyMock.replay(sic2);
  }

  @SuppressWarnings({
    "rawtypes"
  })
  @Test
  public void testRouting() throws Exception {
    logger.debug("Testing routing....");
    DispatcherTestServlet servlet = this.getServletInstance();
    Class controllerClass = RegistrationController.class;
    Method expected = locateMethod(controllerClass, "signupStep1", new Class[] {
        ModelMap.class, HttpServletRequest.class
    });
    Method handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/account_type"));

    expected = locateMethod(controllerClass, "register", new Class[] {
        UserRegistration.class, BindingResult.class, String.class, String.class, ModelMap.class, String.class,
        SessionStatus.class, HttpServletRequest.class
    });

    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/register"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "validateUsername", new Class[] {
      String.class
    });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/validate_username"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "updatePasswordAndVerifyEmail", new Class[] {
        String.class, String.class, HttpServletRequest.class, ModelMap.class, HttpSession.class
    });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/verify_user"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "verifyPhoneVerificationPIN", new Class[] {
        String.class, String.class, HttpServletRequest.class
    });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/phoneverification/verify_pin"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "verifyEmail", new Class[] {
        HttpServletRequest.class, ModelMap.class, HttpSession.class
    });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.GET, "/verify_email"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "requestCall", new Class[] {
        String.class, String.class, HttpServletRequest.class
    });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/request_call"));
    Assert.assertEquals(expected, handler);

    expected = locateMethod(controllerClass, "requestSMS", new Class[] {
        String.class, String.class, HttpServletRequest.class
    });
    handler = servlet.recognize(getRequestTemplate(HttpMethod.POST, "/request_sms"));
    Assert.assertEquals(expected, handler);
  }

  @Test
  public void testSelects() throws Exception {
    List<String> countryNames = Arrays.asList("USA", "SINGAPORE", "INDIA");
    List<String> ccNames = Arrays.asList("AMEX", "VISA", "MASTERCARD", "DISCOVER");

    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));

    /*
     * for (AccountType disposition : registration.getDisposition()) { dispNames.contains(disposition.getName()); }
     */
    for (Country country : registration.getCountryList()) {
      countryNames.contains(country.getName());
    }
    for (CreditCardType card : registration.getCcTypes()) {
      ccNames.contains(card.getName());
    }

  }

  @Test
  public void testRegister() {
    try {
      UserRegistration registration = new UserRegistration();
      registration.setAcceptedTerms(true);
      AccountType disposition = accountTypeDAO.getTrialAccountType();
      setupRegistration(disposition, registration);
      MockHttpServletRequest request = new MockHttpServletRequest();
      DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request);
      RequestContextHolder.setRequestAttributes(webRequest);
      String view = controller.signup(map, null, null, "3", status, new MockHttpServletRequest());
      Assert.assertEquals("register.userinfo", view);
      Assert.assertTrue(map.containsKey("registration"));
      UserRegistration userRegistration = (UserRegistration) map.get("registration");
      Assert.assertNotNull("Account Type Id Should not be null ", userRegistration.getAccountTypeId());
    } catch (Exception e) {
      Assert.fail();

    }
  }

  private void beforeRegisterCall(MockHttpServletRequest request, UserRegistration registration) {
    DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request);
    RequestContextHolder.setRequestAttributes(webRequest);
    request.getSession().setAttribute("phoneVerificationPin", "12345");
    request.getSession().setAttribute("phoneNumber", "919591241025");
    Tenant tenant1 = new Tenant("New Co", accountTypeDAO.getDefaultRegistrationAccountType(), null, randomAddress(),
        true, currencyValueService.locateBYCurrencyCode("USD"), null);
    registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(tenant1));
    registration.setUserEnteredPhoneVerificationPin("12345");
  }

  @Test
  public void testRegisterDefault() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();

    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    registration.setAllowSecondary(true);
    registration.setSecondaryAddress(new Address("steve", "creek", "cupertino", "CHAN", "95014", "IN"));
    AccountType disposition = accountTypeDAO.getDefaultRegistrationAccountType();
    BindingResult result = setupRegistration(disposition, registration);

    beforeRegisterCall(request, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, request);
    Assert.assertEquals("register.registration_success", view);
    Assert.assertTrue(status.isComplete());
    verifyRegistration(disposition, registration.getUser(), registration.getTenant());
    Assert.assertEquals(registration.getTenant().getObject(),
        ((com.citrix.cpbm.access.Tenant) map.get("tenant")).getObject());

  }

  @Test
  public void testRegisterTrial() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/signup?pc=TESTPROMOCODE");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));

    registration.setAcceptedTerms(true);
    AccountType disposition = accountTypeDAO.getTrialAccountType();
    BindingResult result = setupRegistration(disposition, registration);
    PromotionSignup promotionSignup = new PromotionSignup("test" + random.nextInt(), "Citrix",
        "PromotionSignUp@citrix.com");
    promotionSignup.setCreateBy(getRootUser());
    promotionSignup.setCurrency(Currency.getInstance("USD"));
    promotionSignup.setPhone("9999999999");

    CampaignPromotion campaignPromotion = new CampaignPromotion();
    campaignPromotion.setCode("USD" + random.nextInt());
    campaignPromotion.setCreateBy(getRootUser());
    campaignPromotion.setTrial(true);
    campaignPromotion.setUpdateBy(getRootUser());

    CampaignPromotionsInChannels cpic = new CampaignPromotionsInChannels(campaignPromotion,
        channelservice.getDefaultServiceProviderChannel());
    campaignPromotion.getCampaignPromotionsInChannels().add(cpic);
    cmpdao.save(campaignPromotion);

    PromotionToken promotionToken = new PromotionToken(campaignPromotion, "TESTPROMOCODE");
    promotionToken.setCreateBy(getRootUser());
    tokendao.save(promotionToken);

    promotionSignup.setPromotionToken(promotionToken);

    registration.setTrialCode("TESTPROMOCODE");

    DispatcherServletWebRequest webRequest = new DispatcherServletWebRequest(request);
    RequestContextHolder.setRequestAttributes(webRequest);
    request.getSession().setAttribute("phoneVerificationPin", "12345");
    request.getSession().setAttribute("phoneNumber", "919591241025");
    registration.setUserEnteredPhoneVerificationPin("12345");

    String view = controller.register(registration, result, "abc", "abc", map, null, status, request);
    Assert.assertEquals("register.registration_success", view);
    Assert.assertTrue(status.isComplete());
    verifyRegistration(disposition, registration.getUser(), registration.getTenant());
    Assert.assertEquals(registration.getTenant().getAccountId(),
        ((com.citrix.cpbm.access.Tenant) map.get("tenant")).getAccountId());
  }

  @Test
  public void testValidateSuffix() throws Exception {
    Assert.assertEquals("true", controller.validateSuffix("test"));
    asRoot();
    Tenant defaultTenant = getDefaultTenant();
    defaultTenant.setUsernameSuffix("test");
    tenantService.update(defaultTenant);
    Assert.assertEquals("false", controller.validateSuffix("test"));
  }

  @Test
  public void testRegisterBindingHasErrors() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/register");
    request.setRemoteAddr("1.1.1.1");
    User user = new User("test", "test", "testtest.com", "testuser", VALID_PASSWORD, VALID_PHONE, VALID_TIMEZONE, null,
        null, getRootUser());
    user.setAddress(randomAddress());
    Tenant tenant = new Tenant("New Co", accountTypeDAO.getDefaultRegistrationAccountType(), null, randomAddress(),
        true, currencyValueService.locateBYCurrencyCode("USD"), null);
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setUser((com.citrix.cpbm.access.User) CustomProxy.newInstance(user));
    registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(tenant));
    registration.setDisposition(accountTypeDAO.getDefaultRegistrationAccountType());
    BindingResult result = validate(registration);
    beforeRegisterCall(request, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, request);
    Assert.assertEquals("register.userinfo", view);
    Assert.assertFalse(status.isComplete());
    Assert.assertTrue(((UserRegistration) result.getTarget()).getUser().getObject().getId() == 0);
    Assert.assertTrue(((UserRegistration) result.getTarget()).getTenant().getId() == 0);
  }

  @Test
  public void testRegisterUsernameExists() throws Exception {
    User existing = userDAO.findAll(null).get(1);
    String response = controller.validateUsername(existing.getUsername());
    Assert.assertEquals("false", response);
  }

  @Test
  public void testRegisterPostCaptchaFail() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/signup");
    request.setRemoteAddr("1.1.1.1");
    User user = new User("test", "test", "testtest.com", "testuser", VALID_PASSWORD, VALID_PHONE, VALID_TIMEZONE, null,
        null, getRootUser());
    user.setAddress(randomAddress());
    Tenant tenant = new Tenant("New Co", accountTypeDAO.getDefaultRegistrationAccountType(), null, randomAddress(),
        true, currencyValueService.locateBYCurrencyCode("USD"), null);
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setUser((com.citrix.cpbm.access.User) CustomProxy.newInstance(user));
    registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(tenant));
    BindingResult result = new BindException(registration, "registration");
    beforeRegisterCall(request, registration);
    String view = controller.register(registration, result, "abc", "CAPTCHA_FAIL", map, "1", status, request);
    Assert.assertEquals("register.moreuserinfo", view);
    Assert.assertFalse(status.isComplete());
    Assert.assertTrue(result.hasGlobalErrors());
    Assert.assertTrue(result.getGlobalErrorCount() == 1);
    Assert.assertEquals("errors.registration.captcha", result.getGlobalError().getCode());
    Assert.assertEquals("captcha.error", map.get("registrationError"));
  }

  @Test
  public void testRegisterTrialForInvalidPromoCode() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/signup?pc=testpromo");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    AccountType disposition = accountTypeDAO.getTrialAccountType();
    BindingResult result = setupRegistration(disposition, registration);
    PromotionSignup promotionSignup = new PromotionSignup("test" + random.nextInt(), "Citrix",
        "PromotionSignUp@citrix.com");
    promotionSignup.setCreateBy(getRootUser());
    promotionSignup.setCurrency(Currency.getInstance("USD"));
    promotionSignup.setPhone("9999999999");

    CampaignPromotion campaignPromotion = new CampaignPromotion();
    campaignPromotion.setCode("USD" + random.nextInt());
    campaignPromotion.setCreateBy(getRootUser());
    campaignPromotion.setTrial(true);
    campaignPromotion.setUpdateBy(getRootUser());
    campaignpromotiondao.save(campaignPromotion);

    PromotionToken promotionToken = new PromotionToken(campaignPromotion, "TESTPROMOCODE");
    promotionToken.setCreateBy(getRootUser());
    tokendao.save(promotionToken);

    promotionSignup.setPromotionToken(promotionToken);
    registration.setTrialCode("testpromo");
    beforeRegisterCall(request, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, request);
    Assert.assertEquals("register.fail", view);
    Assert.assertFalse(status.isComplete());

  }

  @Test
  public void testRegisterNotAcceptedTerms() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    AccountType disposition = accountTypeDAO.getOnDemandPostPaidAccountType();
    BindingResult result = setupRegistration(disposition, registration);
    beforeRegisterCall(request, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, request);
    Assert.assertEquals("register.userinfo", view);
    Assert.assertFalse(status.isComplete());
    Assert.assertTrue(result.hasFieldErrors());
    Assert.assertTrue(result.getFieldErrorCount() == 1);
    Assert.assertEquals("AssertTrue", result.getFieldError("acceptedTerms").getCode());
  }

  @Test
  public void testValidateUsername() throws Exception {
    asAnonymous();
    User existing = userDAO.findAll(null).get(0);
    String response = controller.validateUsername(existing.getUsername());
    Assert.assertFalse(Boolean.parseBoolean(response));

    response = controller.validateUsername("nonexistent");
    Assert.assertTrue(Boolean.parseBoolean(response));
  }

  @Test
  public void testVerifyEmail() throws Exception {
    User user = createDisabledUser();
    String auth = user.getAuthorization(0);

    MockHttpSession session = new MockHttpSession();
    session.setAttribute("regAuth", auth);
    session.setAttribute("regParam", user.getParam());

    String view = controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, session);
    String redirect = "redirect:/?verify";

    Assert.assertEquals(redirect, view);
    userDAO.flush();
    User found = userDAO.find(user.getId());
    Assert.assertEquals(user, found);
    Assert.assertTrue(found.isEnabled());

  }

  @SuppressWarnings("unchecked")
  @Test
  public void testGetLoginPageUIRelatedConfigs() {
    HashMap<String, Object> configs = controller.getLoginPageUIRelatedConfigs();
    Assert.assertEquals(4, configs.size());
    Assert.assertEquals("false", configs.get("isDirectoryServiceAuthenticationON"));
    Assert.assertEquals("N", configs.get("showSuffix"));
    Assert.assertEquals("true", configs.get("showSuffixDropBox"));
    List<String> suffixList = (List<String>) configs.get("suffixList");
    Assert.assertEquals(0, suffixList.size());

    Configuration configuration = configurationService
        .locateConfigurationByName(Names.com_citrix_cpbm_portal_directory_service_enabled);
    configuration.setValue("true");
    configurationService.update(configuration);

    configuration = configurationService.locateConfigurationByName(Names.com_citrix_cpbm_directory_mode);
    configuration.setValue("pull");
    configurationService.update(configuration);

    configs = controller.getLoginPageUIRelatedConfigs();
    Assert.assertEquals(4, configs.size());
    Assert.assertEquals("true", configs.get("isDirectoryServiceAuthenticationON"));
    Assert.assertEquals("N", configs.get("showSuffix"));
    Assert.assertEquals("true", configs.get("showSuffixDropBox"));
    suffixList = (List<String>) configs.get("suffixList");
    Assert.assertEquals(0, suffixList.size());

    configuration = configurationService.locateConfigurationByName(Names.com_citrix_cpbm_username_duplicate_allowed);
    configuration.setValue("Y");
    configurationService.update(configuration);

    configs = controller.getLoginPageUIRelatedConfigs();
    Assert.assertEquals(4, configs.size());
    Assert.assertEquals("true", configs.get("isDirectoryServiceAuthenticationON"));
    Assert.assertEquals("Y", configs.get("showSuffix"));
    Assert.assertEquals("true", configs.get("showSuffixDropBox"));
    suffixList = (List<String>) configs.get("suffixList");
    Assert.assertEquals(0, suffixList.size());

    configuration = configurationService
        .locateConfigurationByName(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled);
    configuration.setValue("false");
    configurationService.update(configuration);

    configs = controller.getLoginPageUIRelatedConfigs();
    Assert.assertEquals(4, configs.size());
    Assert.assertEquals("true", configs.get("isDirectoryServiceAuthenticationON"));
    Assert.assertEquals("Y", configs.get("showSuffix"));
    Assert.assertEquals("false", configs.get("showSuffixDropBox"));
    suffixList = (List<String>) configs.get("suffixList");
    Assert.assertEquals(0, suffixList.size());
  }

  @Test
  public void testVerifyEmailWithNoPasswordSet() throws Exception {
    User user = createUserWithoutPassword();
    String auth = user.getAuthorization(0);

    MockHttpSession session = new MockHttpSession();
    session.setAttribute("regAuth", auth);
    session.setAttribute("regParam", user.getParam());

    String view = controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, session);
    String redirect = "register.setpassword";

    Assert.assertEquals(redirect, view);
    userDAO.flush();
  }

  @Test(expected = UserAuthorizationInvalidException.class)
  public void testVerifyEmailBadAuth() throws Exception {
    User user = createDisabledUser();

    MockHttpSession session = new MockHttpSession();
    session.setAttribute("regAuth", "garbage");
    session.setAttribute("regParam", user.getParam());

    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, session);
  }

  @Test(expected = UserAuthorizationInvalidException.class)
  public void testVerifyEmailWrongAuth() throws Exception {
    User user = createDisabledUser();
    String auth = user.getAuthorization(1);
    MockHttpSession session = new MockHttpSession();
    session.setAttribute("regAuth", auth);
    session.setAttribute("regParam", user.getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, new MockHttpSession());
  }

  @Test
  public void testVerifyUserPasswordNotSet() {
    User user = createUserWithoutPassword();
    String auth = user.getAuthorization(1);
    String view = controller.updatePasswordAndVerifyEmail(auth, user.getParam(), new MockHttpServletRequest(), map,
        new MockHttpSession());
    String expectedView = "register.setpassword";
    Assert.assertEquals(view, expectedView);
  }

  @Test
  public void testVerifyUserPasswordNotSetWithDirectoryServerPullOn() {
    Configuration configuration = configurationService
        .locateConfigurationByName(Names.com_citrix_cpbm_portal_directory_service_enabled);
    configuration.setValue("true");
    configurationService.update(configuration);

    configuration = configurationService.locateConfigurationByName(Names.com_citrix_cpbm_directory_mode);
    configuration.setValue("pull");
    configurationService.update(configuration);

    User user = createUserWithoutPassword();
    String auth = user.getAuthorization(1);
    String view = controller.updatePasswordAndVerifyEmail(auth, user.getParam(), new MockHttpServletRequest(), map,
        new MockHttpSession());
    String expectedView = "redirect:/portal/verify_email";
    Assert.assertEquals(view, expectedView);
  }

  @Test
  public void testVerifyUserEmailNotVerified() {
    User user = createUserWithoutEmailVerification();
    String auth = user.getAuthorization(1);
    String view = controller.updatePasswordAndVerifyEmail(auth, user.getParam(), new MockHttpServletRequest(), map,
        new MockHttpSession());
    String expectedView = "redirect:/portal/verify_email";
    Assert.assertEquals(view, expectedView);
  }

  @Test
  public void testVerifyEnabledUser() {
    User user = createEmailVerifiedUser();
    String auth = user.getAuthorization(1);
    String view = controller.updatePasswordAndVerifyEmail(auth, user.getParam(), new MockHttpServletRequest(), map,
        new MockHttpSession());
    String expectedView = "redirect:/portal/login";
    Assert.assertEquals(view, expectedView);
  }

  private User createDisabledUser() {
    User user = new User("first", "last", "verify@verify.com", "disableduser", VALID_PASSWORD, VALID_PHONE,
        VALID_TIMEZONE, getDefaultTenant(), userProfile, getRootUser());
    userDAO.save(user);
    userDAO.flush();
    return user;
  }

  private User createUserWithoutEmailVerification() {
    User user = new User("first1", "last1", "verify1@verify.com", "disableduser", VALID_PASSWORD, VALID_PHONE,
        VALID_TIMEZONE, getDefaultTenant(), userProfile, getRootUser());
    user.setEmailVerified(false);
    userDAO.save(user);
    userDAO.flush();
    return user;
  }

  private User createUserWithoutPassword() {
    User user = new User("first2", "last2", "verify2@verify.com", "disableduser", null, VALID_PHONE, VALID_TIMEZONE,
        getDefaultTenant(), userProfile, getRootUser());
    userDAO.save(user);
    userDAO.flush();
    return user;
  }

  private User createEmailVerifiedUser() {
    User user = new User("first", "last", "verify@verify.com", "disableduser", VALID_PASSWORD, VALID_PHONE,
        VALID_TIMEZONE, getDefaultTenant(), userProfile, getRootUser());
    user.setEmailVerified(true);
    userDAO.save(user);
    userDAO.flush();
    return user;
  }

  private BindingResult setupRegistration(AccountType disposition, UserRegistration registration) throws Exception {
    String rand = "test" + random.nextInt();
    Address address = randomAddress();
    User user = new User("test", "test", rand + "@test.com", rand, VALID_PASSWORD, VALID_PHONE, VALID_TIMEZONE, null,
        null, null);
    user.setAddress(address);
    Tenant tenant = new Tenant("New Co", disposition, null, address, true,
        currencyValueService.locateBYCurrencyCode("USD"), null);
    registration.setUser((com.citrix.cpbm.access.User) CustomProxy.newInstance(user));
    registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(tenant));
    registration.setDisposition(disposition);
    registration.setAccountTypeId(disposition.getId() + "");
    BindingResult result = validate(registration);
    return result;
  }

  private void verifyRegistration(AccountType disposition, com.citrix.cpbm.access.User user,
      com.citrix.cpbm.access.Tenant tenant) {
    Assert.assertTrue(user.getObject().getId() != 0);
    Assert.assertTrue(tenant.getObject().getId() != 0);
    User foundUser = userDAO.find(user.getObject().getId());
    Assert.assertEquals(user, foundUser);
    Assert.assertEquals(getPortalUser(), user.getObject().getCreatedBy());
    Assert.assertFalse(foundUser.isEnabled());
    tenantDAO.merge(tenant.getObject());
    Tenant foundTenant = tenantDAO.find(tenant.getId());
    Assert.assertEquals(tenant, foundTenant);
    Assert.assertEquals(getPortalUser(), tenant.getObject().getCreatedBy());
    Assert.assertEquals(foundUser, tenant.getOwner());
    Assert.assertEquals(foundUser, foundTenant.getOwner());
    Assert.assertEquals(foundTenant, foundUser.getTenant());
    Assert.assertNotNull(foundTenant.getAccountId());
    Assert.assertTrue(ACCOUNT_NUMBER_PATTERN.matcher(foundTenant.getAccountId()).matches());
    Assert.assertEquals(disposition, foundTenant.getAccountType());
    Assert.assertEquals(disposition.getSupportedPaymentModes().get(0), foundTenant.getTenantExtraInformation()
        .getPaymentMode());
    Assert.assertEquals(currencyValueDAO.findByCurrencyCode("USD"), foundTenant.getCurrency());
  }

  @Test
  public void testRequestCall() throws JsonGenerationException, JsonMappingException, IOException {
    request.getSession().setAttribute("phoneVerificationPin", "12345");
    Map<String, String> keyvaluepairs = controller.requestCall("INVALIDNUMBER", "INVALIDCODE", request);

    try {
      Assert.assertTrue("failed".equalsIgnoreCase(keyvaluepairs.get("result")));

      Map<String, String> keyvaluepairs1 = controller.requestCall("123456", "91", request);
      Assert.assertTrue("success".equalsIgnoreCase(keyvaluepairs1.get("result")));
    } catch (Exception e) {

    }

    try {
      request.getSession().setAttribute("phoneVerificationPin", "ABC");
      keyvaluepairs = controller.requestCall("INVALIDNUMBER", "INVALIDCODE", request);
      Assert.assertTrue("failed".equalsIgnoreCase(keyvaluepairs.get("result")));

      Map<String, String> keyvaluepairs1 = controller.requestCall("123456", "91", request);
      Assert.assertTrue("failed".equalsIgnoreCase(keyvaluepairs1.get("result")));
    } catch (Exception e) {

    }
  }

  @Test
  public void testRequestSMS() throws JsonGenerationException, JsonMappingException, IOException {
    request.getSession().setAttribute("phoneVerificationPin", "12345");
    Map<String, String> keyvaluepairs = controller.requestSMS("INVALIDNUMBER", "INVALIDCODE", request);
    Assert.assertEquals("failed", keyvaluepairs.get("result"));

    Map<String, String> keyvaluepairs1 = controller.requestSMS("123456", "91", request);
    Assert.assertEquals("success", keyvaluepairs1.get("result"));
  }

  @Test
  public void testManualActivationFlag() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    AccountType disposition = accountTypeDAO.getDefaultRegistrationAccountType();
    disposition.setManualActivation(true);
    BindingResult result = setupRegistration(disposition, registration);
    beforeRegisterCall(request, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, request);
    Assert.assertEquals(2, eventListener.getEvents().size());
    PortalEvent event = eventListener.getEvents().get(0);
    Assert.assertTrue(event.getPayload() instanceof VerifyEmailRequest);
    Assert.assertEquals("register.registration_success", view);
    Assert.assertTrue(status.isComplete());
    verifyRegistration(disposition, registration.getUser(), registration.getTenant());
    Assert.assertEquals(registration.getTenant().getObject(),
        ((com.citrix.cpbm.access.Tenant) map.get("tenant")).getObject());
  }

  @Test
  public void testVerifyPhoneVerificationPIN() throws Exception {
    request.getSession().setAttribute("phoneVerificationPin", "12345");
    request.getSession().setAttribute("phoneNumber", "123456789");
    String failedResult = controller.verifyPhoneVerificationPIN("54321", "123456789", request);
    Assert.assertEquals("failed", failedResult);

    String successResult = controller.verifyPhoneVerificationPIN("12345", "123456789", request);
    Assert.assertEquals("success", successResult);

  }

  @Test
  public void testEmailVerifiedEventForManualActivationAccountType() {
    // Sign up for manual activation account type
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    List<AccountType> accountTypes = accountTypeDAO.getManualRegistrationAccountTypes();
    AccountType disposition = null;
    for (AccountType accountType : accountTypes) {
      if (accountType.isManualActivation()) {
        disposition = accountType;
      }
    }
    BindingResult result = null;
    try {
      result = setupRegistration(disposition, registration);
    } catch (Exception e) {
      e.printStackTrace();
    }
    beforeRegisterCall(request, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, request);
    Assert.assertEquals("register.registration_success", view);
    Assert.assertTrue(status.isComplete());
    verifyRegistration(disposition, registration.getUser(), registration.getTenant());
    Assert.assertEquals(registration.getTenant().getObject(),
        ((com.citrix.cpbm.access.Tenant) map.get("tenant")).getObject());
    // account activation request event
    Assert.assertEquals(2, eventListener.getEvents().size());
    PortalEvent verifyEmailRequest = eventListener.getEvents().get(0);
    Assert.assertTrue(verifyEmailRequest.getPayload() instanceof VerifyEmailRequest);
    eventListener.clear();
    // verify email
    String auth = registration.getUser().getObject().getAuthorization(0);
    MockHttpSession session = new MockHttpSession();
    session.setAttribute("regAuth", auth);
    session.setAttribute("regParam", registration.getUser().getObject().getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, session);
    // Since tenant is not at activated, we will get only Welcome email
    Assert.assertEquals(1, eventListener.getEvents().size());
    PortalEvent event = eventListener.getEvents().get(0);
    Assert.assertTrue(event.getPayload() instanceof EmailVerified);
  }

  @Test
  public void testWelcomeEmailEventForRetail() {
    // Sign up for manual activation account type
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    AccountType disposition = accountTypeDAO.getDefaultSelfRegistrationAccountType();
    BindingResult result = null;
    try {
      result = setupRegistration(disposition, registration);
    } catch (Exception e) {
      e.printStackTrace();
    }
    beforeRegisterCall(request, registration);
    controller.register(registration, result, "abc", "abc", map, null, status, request);
    // Tenant Activation Event
    // Assert.assertEquals(1, eventListener.getEvents().size());
    // PortalEvent tenantActivationEvent = eventListener.getEvents().get(0);
    // Assert.assertTrue(tenantActivationEvent.getPayload() instanceof TenantActivation);
    eventListener.clear();
    // verify email
    String auth = registration.getUser().getObject().getAuthorization(0);
    MockHttpSession session = new MockHttpSession();
    session.setAttribute("regAuth", auth);
    session.setAttribute("regParam", registration.getUser().getObject().getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, session);
    // Since tenant is at activated, we will get Email Verified event
    Assert.assertEquals(1, eventListener.getEvents().size());
  }

  @Test
  public void testWelcomeEmailAndActivationEmailEventsForRetail() {
    // Sign up for manual activation account type
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    AccountType disposition = accountTypeDAO.getDefaultSelfRegistrationAccountType();
    BindingResult result = null;
    try {
      result = setupRegistration(disposition, registration);
    } catch (Exception e) {
      e.printStackTrace();
    }
    beforeRegisterCall(request, registration);
    controller.register(registration, result, "abc", "abc", map, null, status, request);
    // Tenant Activation Event
    // Assert.assertEquals(1, eventListener.getEvents().size());
    // PortalEvent tenantActivationEvent = eventListener.getEvents().get(0);
    // Assert.assertTrue(tenantActivationEvent.getPayload() instanceof TenantActivation);
    eventListener.clear();
    // verify email
    String auth = registration.getUser().getObject().getAuthorization(0);
    MockHttpSession session = new MockHttpSession();
    session.setAttribute("regAuth", auth);
    session.setAttribute("regParam", registration.getUser().getObject().getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, session);
    // Since tenant is at activated, we will get only Welcome email and ActivationEmail events
    Assert.assertEquals(1, eventListener.getEvents().size());
  }

  @Test
  public void testWelcomeEmailAndActivationEmailEventsForCorporate() {
    // Sign up for manual activation account type
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setAcceptedTerms(true);
    List<AccountType> accountTypes = accountTypeDAO.getManualRegistrationAccountTypes();
    AccountType disposition = null;
    for (AccountType accountType : accountTypes) {
      if (accountType.isManualActivation()) {
        disposition = accountType;
      }
    }
    BindingResult result = null;
    try {
      result = setupRegistration(disposition, registration);
    } catch (Exception e) {
      e.printStackTrace();
    }
    beforeRegisterCall(request, registration);
    controller.register(registration, result, "abc", "abc", map, null, status, request);
    // Tenant Activation Event
    // Assert.assertEquals(1, eventListener.getEvents().size());
    // PortalEvent accountActivationRequestEvent = eventListener.getEvents().get(0);
    // Assert.assertTrue(accountActivationRequestEvent.getPayload() instanceof AccountActivationRequestEvent);
    eventListener.clear();

    // verify email
    String auth = registration.getUser().getObject().getAuthorization(0);
    MockHttpSession session = new MockHttpSession();
    session.setAttribute("regAuth", auth);
    session.setAttribute("regParam", registration.getUser().getObject().getParam());
    controller.verifyEmail(getRequestTemplate(HttpMethod.GET, "/verify_email"), map, session);
    // Since tenant is at activated, we will get EmailVerified Event
    Assert.assertEquals(1, eventListener.getEvents().size());
    eventListener.clear();

    Tenant tenant = tenantService.get(registration.getTenant().getUuid());
    completeBusinessTransactionsForTenant(tenant);
    tenantService.changeState(registration.getTenant().getUuid(), "ACTIVE", null, "Manual");
    PortalEvent tenantActivationEvent = eventListener.getEvents().get(0);
    Assert.assertTrue(tenantActivationEvent.getPayload() instanceof TenantActivation);
    eventListener.clear();
  }

  @Test
  public void testTrialRegister() {
    Channel channel = channelservice.locateChannel("Channel2");
    String register = controller.trialRegister("trial_camp", "Channel2", map);
    Assert.assertEquals(register, new String("register.userinfo"));
    Assert.assertEquals(map.get("title"), new String("page.order_now"));
    Assert.assertEquals(map.get("homeUrl"), new String("http://www.cloud.com"));
    Assert.assertEquals(map.get("cloudmktgUrl"), new String("http://www.cloud.com"));
    Assert.assertNotNull(map.get("registration"));
    UserRegistration registration = (UserRegistration) map.get("registration");
    Assert.assertNotNull(registration.getTrialCode());
    Assert.assertNotNull(registration.getTenant());
    Assert.assertEquals(map.get("channelParam"), channel.getParam());
    register = controller.trialRegister("trial_camp", null, map);
    Assert.assertEquals(register, new String("register.userinfo"));
  }

  @Test
  public void testInvalidTrailRegister() {

    try {
      Assert.assertEquals(controller.trialRegister("wrong_trialcode", null, map), new String("trial.invalid"));
      Assert.fail();
    } catch (IllegalArgumentException e) {
    }

  }

  @Test
  public void testsetPassword() {

    User user = createUserWithoutPassword();
    Assert.assertNull(user.getPassword());
    session.setAttribute("regParam", user.getParam());
    String setPassword = controller.setPassword("Test123#", session);
    Assert.assertNotNull(user.getPassword());
    Assert.assertEquals(setPassword, new String("redirect:/portal/verify_email"));
    Assert.assertTrue(user.authenticate("Test123#"));
  }

  @Test
  public void testback() {
    Tenant tenant = tenantService.getTenantByParam("id", "1", false);
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    registration.setTenant((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(tenant));
    String back = controller.back(registration, map);
    Assert.assertEquals(back, new String("register.userinfo"));
    Assert.assertEquals(map.get("title"), new String("page.order_now"));
    Assert.assertEquals(map.get("registration"), registration);
    Assert.assertEquals(((com.citrix.cpbm.access.Tenant) map.get("tenant")).getAccountId(), registration.getTenant()
        .getAccountId());
    Assert.assertEquals(map.get("page"), Page.HOME);
    Assert.assertEquals(map.get("cloudmktgUrl"), new String("http://www.cloud.com"));

  }

  @Test
  public void testutilityratesLightbox() {
    String utilityrates = controller.utilityratesLightbox("0bd2ab86-7402-4815-b785-55c8d9090580", "USD", null, null,
        map);
    Assert.assertNotNull(utilityrates);
    Assert.assertTrue(map.containsAttribute("currency"));
    Assert.assertTrue(map.containsAttribute("startDate"));
    Assert.assertEquals(map.get("currency"), currencyValueService.locateBYCurrencyCode("USD"));
    Assert.assertNotNull(map.get("startDate"));
    utilityrates = controller.utilityratesLightbox("0bd2ab86-7402-4", "USD", null, null, map);
    Assert.assertNotNull(utilityrates);
    Assert.assertTrue(map.containsAttribute("currency"));
    Assert.assertTrue(map.containsAttribute("startDate"));
    Assert.assertEquals(map.get("currency"), currencyValueService.locateBYCurrencyCode("USD"));
    Assert.assertNotNull(map.get("startDate"));
  }

  /*
   * Description : Test signup with promocode added in channel. Author : Avinashg
   */
  @Test
  public void testPromoCodeAddedInGivenChannel() throws Exception {
    AccountType accountType = accountTypeDAO.find("3");

    Channel actualChannel = channelDAO.find(3L);
    Tenant tenant2 = new Tenant("Acme Corp " + random.nextInt(), accountType, null, randomAddress(), true,
        currencyValueDAO.findByCurrencyCode("USD"), null);
    com.citrix.cpbm.access.Tenant tenant1 = (com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(tenant2);
    UserRegistration userRegistration = new UserRegistration();
    userRegistration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    userRegistration.setTenant(tenant1);
    userRegistration.setAccountTypeId("3");
    controller.signup(map, campaignpromotiondao.find("1").getCode(), actualChannel.getCode(), "3", status, request);
    Assert.assertEquals(actualChannel.getParam(), map.get("channelParam"));

  }

  @Test
  public void testSignupStep1() {
    ModelMap model = new ModelMap();
    String register = controller.signupStep1(model, request);
    Assert.assertEquals(register, new String("register.account_type"));
  }

  @Test
  public void testUserInfo() {
    ModelMap model = new ModelMap();
    UserRegistration registration = new UserRegistration();
    registration.setAcceptedTerms(true);
    AccountType disposition = accountTypeDAO.getTrialAccountType();
    BindingResult result;
    try {
      result = setupRegistration(disposition, registration);
      String register = controller.userInfo(registration, result, model, null, status, request);
      Assert.assertEquals("register.moreuserinfo", register);
    } catch (Exception e) {
      Assert.fail();
    }

  }

  @Test
  public void testListAnonymousProductBundles() {
    List<ProductBundleRevision> productBundleRevisions = controller.listAnonymousProductBundles(getDefaultTenant()
        .getSourceChannel().toString(), "USD", false, null);
    Assert.assertNotNull(productBundleRevisions);
  }

  @Test
  public void testPhoneverification() {
    ModelMap model = new ModelMap();
    UserRegistration registration = new UserRegistration();
    List<Country> countryList = new ArrayList<Country>();
    countryList.addAll(countryService.getCountries(null, null, null, 1, 12, null, false));
    registration.setCountryList(countryList);
    AccountType disposition = accountTypeDAO.getTrialAccountType();
    BindingResult result;
    try {
      result = setupRegistration(disposition, registration);
      String value = controller.phoneverification(registration, result, "abs", "abs", model, null, status, request);
      Assert.assertEquals(value, new String("register.phoneverification"));
    } catch (Exception e) {
      Assert.fail();
    }
    try {
      result = setupRegistration(disposition, registration);
      controller.phoneverification(registration, result, "abs", null, model, null, status, request);
    } catch (Exception e) {
      Assert.fail();
    }
    try {
      countryList = null;
      result = setupRegistration(disposition, registration);
      controller.phoneverification(registration, result, "abs", null, model, null, status, request);
      Assert.assertTrue(true);
    } catch (Exception e) {
      Assert.fail();
    }

  }

  @Test
  public void testValidateMailDomain() {
    String value = controller.validateMailDomain(VALID_EMAIL);
    Assert.assertNotNull(value);
  }

  @Test
  public void testUserInfoWithIntranetOnlyModeEnabled() throws Exception {
    configurationService.clearConfigurationCache(true, "");
    com.vmops.model.Configuration isIntranetModeEnabled = configurationService
        .locateConfigurationByName(Names.com_citrix_cpbm_use_intranet_only);
    isIntranetModeEnabled.setValue("true");
    configurationService.update(isIntranetModeEnabled);

    ModelMap model = new ModelMap();
    UserRegistration registration = new UserRegistration();
    AccountType disposition = accountTypeDAO.getTrialAccountType();
    BindingResult result;
    registration.setAcceptedTerms(true);
    result = setupRegistration(disposition, registration);
    String view = controller.userInfo(registration, result, model, null, status, request);
    Assert.assertEquals("register.moreuserinfo", view);
    Assert.assertFalse(model.containsKey("showCaptcha"));
    Assert.assertFalse(model.containsKey("recaptchaPublicKey"));

  }

  @Test
  public void testUserInfoWithIntranetOnlyModeDisabled() throws Exception {
    configurationService.clearConfigurationCache(true, "");
    com.vmops.model.Configuration isIntranetModeEnabled = configurationService
        .locateConfigurationByName(Names.com_citrix_cpbm_use_intranet_only);
    isIntranetModeEnabled.setValue("false");
    configurationService.update(isIntranetModeEnabled);

    ModelMap model = new ModelMap();
    UserRegistration registration = new UserRegistration();
    AccountType disposition = accountTypeDAO.getTrialAccountType();
    BindingResult result;
    registration.setAcceptedTerms(true);
    result = setupRegistration(disposition, registration);
    String view = controller.userInfo(registration, result, model, null, status, request);
    Assert.assertEquals("register.moreuserinfo", view);
    Assert.assertTrue(model.containsKey("showCaptcha"));
    Assert.assertTrue(Boolean.valueOf(model.get("showCaptcha").toString()));
    Assert.assertTrue(model.containsKey("recaptchaPublicKey"));

  }
}


text:
package org.eclipse.jface.text.contentassist;

/**
 * Extends {@link org.eclipse.jface.text.contentassist.IContextInformation} with
 * the ability to freely position the context information.
 *
 * @since 2.0
 */
public interface IContextInformationExtension {

	/**
	 * Returns the start offset of the range for which this context
	 * information is valid or <code>-1</code> if unknown.
	 *
	 * @return the start offset of the range for which this context
	 *         information is valid
	 */
	int getContextInformationPosition();
}

redpajama_set_name: RedPajamaGithub


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

<TITLE>
GinScopedBindingBuilder
</TITLE>

<META NAME="date" CONTENT="2011-02-21">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.gwt.inject.client.binder

Interface GinScopedBindingBuilder

All Known Subinterfaces:
GinAnnotatedBindingBuilder<T>, GinLinkedBindingBuilder<T>

public interface GinScopedBindingBuilder

Method Summary

 void
asEagerSingleton()

 void
in(java.lang.Class<? extends java.lang.annotation.Annotation> scopeAnnotation)

Method Detail

in

void in(java.lang.Class<? extends java.lang.annotation.Annotation> scopeAnnotation)

asEagerSingleton

void asEagerSingleton()

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package im.actor.runtime.crypto.ratchet;

import im.actor.runtime.crypto.Curve25519;

// Disabling Bounds checks for speeding up calculations

/*-[
#define J2OBJC_DISABLE_ARRAY_BOUND_CHECKS 1
]-*/

public class RatchetPrivateKey extends RatchetPublicKey {

    private final byte[] privateKey;

    public RatchetPrivateKey(byte[] privateKey) {
        super(Curve25519.keyGenPublic(privateKey));

        this.privateKey = privateKey;
    }

    public byte[] getPrivateKey() {
        return privateKey;
    }
}


text:
layout: post
title: "Continuous Learning"
date: 2014-02-10 15:07
author: steven.murawski@gmail.com
comments: true
categories: []
tags: []
---

# The Background

A few weeks ago, [Richard Campbell](http://twitter.com/richcampbell) posted a note on Twitter that he'd be talking to [Kim Tripp](http://twitter.com/KimberlyLTripp) about learning in the technology space for [Runas Radio](http://runasradio.com).  Richard asked if there were any questions we'd like answered, and I replied with a question.

[@richcampbell](https://twitter.com/richcampbell) [@KimberlyLTripp](https://twitter.com/KimberlyLTripp) Whose responsibility is it to find the time for improving skills? Employer or Employee [#RunAsRadio](https://twitter.com/search?q=%23RunAsRadio&src=hash)
— Steven Murawski (@StevenMurawski) [January 28, 2014](https://twitter.com/StevenMurawski/statuses/428285061298126848)

Kim responded via Twitter that afternoon.

[@StevenMurawski](https://twitter.com/StevenMurawski) [@richcampbell](https://twitter.com/richcampbell) Great question. We spent time on this one. It's a bit of both. Employer = money. Employee = commitment
— Kimberly L. Tripp (@KimberlyLTripp) [January 28, 2014](https://twitter.com/KimberlyLTripp/statuses/428304615134605312)

And also on the [Runas Radio show](http://runasradio.com/default.aspx?showNum=354), which was recently posted.  In the show, Richard and Kim discussed a good bit about the topic.  They had a good talk around the topic (it's worth a listen and the show is not that long - about a half hour).  They provide some great tips for working with your employer to get training.

# Whose Responsibility Is It?

While I think that employers should invest in training their employees, I think Richard and Kim missed the intent of my question, either due to my failings as a communicator or a problem with the medium of communication.  My intent was to identify who was ultimately responsible for ensuring that your skills as an employee progress.

It is the **employee's** responsibility to get training.   The employer should help and make resources available, but it is your career, your life, your skills.

## Yes You

Regardless of what training opportunities are available at your company, you are in charge of your career.  In order to protect your career or improve your position, you need to continually be learning.  Whether it's video training, reading books, building a home lab, participating in open source, or going to conferences, you need to do something to maintain and improve your skills.

## This Will Bite You

If you don't keep your skills current, this will come back to bite you when you look to change roles or move up in your organization.

If you want to increase your standing in your organization to a more managerial role, you need to build your "soft skills" and learn your business domain.

If you want to deepen your technical expertise, you need to dig deeper into your chosen area (not necessarily what you are currently working on) AND broaden your understanding of the surrounding technology landscape.

# Why It Matters

I've recently had the opportunity to talk to a handful of people who work in very different environments than mine.  Most have been in their current environments for 5 to 20 years.  Most of those environments are stuck back in the Server 2003 era, with either XP or Windows 7 on the desktop.  Most of those people haven't really looked at Server 2008 R2, which is already almost 5 years old.  Server 2008 R2 is already two major versions back from the currently released OS.  It only has one more year under mainstream support.

The pace of change is increasing.  If your only experience is managing environments full of Server 2003 and you haven't keeping up on the changes in management or OS, good luck when you try to move to a role (either in your current org or somewhere else) that uses a newer platform, you'll be at a major disadvantage.  There have been some major platform shifts from Server 2003 to Server 2008 and from Server 2008 R2 to 2012.

## Don't Be Left Behind

I've been "fortunate" to be an early adopter, either through the old IT Pro Momentum program or via the Technology Adoption Programs (TAP), through most of my career.  Even when I wasn't, I was playing with the newer platforms as soon as they were accessible.  This prepared me to step in to roles that leveraged this newer technology more easily.

We are currently interviewing people for a couple of sysadmin focused roles at Stack Exchange.

*   How will you respond when I ask about your experience with PowerShell 3 or 4?
*   What do you know about Puppet or DSC?
*   Do you understand why CIM and WSMAN are important?


text:
import React from "react";
import { TcText } from "@times-components/utils";
import Enzyme, { mount } from "enzyme";
import React16Adapter from "enzyme-adapter-react-16";
import {
  addSerializers,
  compose,
  enzymeRenderedSerializer,
  hoistStyle,
  hoistStyleTransform,
  stylePrinter
} from "../../src";

Enzyme.configure({ adapter: new React16Adapter() });

const styles = {
  text: {
    color: "yellow"
  }
};

describe("hoist-style should", () => {
  it("hoist a style and leave existing props untouched", () => {
    addSerializers(expect, enzymeRenderedSerializer(), hoistStyle);

    const wrapper = mount(
      <TcText foo="bar" style={{ ...styles.text, color: "red" }}>
        Some text
      </TcText>
    );

    expect(wrapper).toMatchSnapshot();
  });

  it("hoist a style as well as an rnw class", () => {
    addSerializers(
      expect,
      enzymeRenderedSerializer(),
      compose(
        stylePrinter,
        hoistStyleTransform
      )
    );

    const wrapper = mount(
      <TcText foo="bar" style={{ ...styles.text, color: "red" }}>
        Some text
      </TcText>
    );

    expect(wrapper).toMatchSnapshot();
  });
});


text:
<script>
document.testExpando = "It's me too!";

parent.childEval = eval;

parent.childEvalCaller = (function()
{
    // Capture window.window into a variable, since this property always returns null once
    // the context is navigated.
    var w = window;
    return function(s) {
        return w.eval(s);
    }
})();

parent.childLocalEvalCaller = (function()
{
    var e = eval;
    return function(s) { return e(s); };
})();

location.href = "http://localhost:8000/security/resources/xss-eval3.html";
</script>


text:
Gia H. Ngo, Simon B. Eickhoff, Minh Nguyen, Peter T. Fox,  R. Nathan Spreng, B. T. Thomas Yeo. [**Beyond Consensus: Embracing Heterogeneity in Curated Neuroimaging Meta-Analysis**](https://www.sciencedirect.com/science/article/abs/pii/S1053811919305282). NeuroImage, 200:142-158, 2019

Gia H. Ngo, Simon B. Eickhoff, Peter T. Fox, B. T. Thomas Yeo. [**Collapsed variational Bayesian inference of the author-topic model: application to large-scale coordinate-based meta-analysis**](https://ieeexplore.ieee.org/document/7552332). In 2016 international workshop on pattern recognition in neuroimaging (PRNI), pp. 1-4. IEEE, 2016.

----

## Overview

This project provides all functions necessary to perform a coordinate-based meta-analysis using the author-topic model, such as to estimate cognitive components of a functional domain (e.g. self-generated thought) or estimate the co-activation patterns of a seed region (e.g. inferior frontal junction).

1. [SelfGeneratedThought](./SelfGeneratedThought) folder contains data and instruction to discover cognitive components of the functional domain of self-generated thought.
2. [CoactivationMappingIFJ](./CoactivationMappingIFJ) folder contains instruction to estimate the co-activation patterns of a seed region such as the inferior frontal junction (IFJ).
3. [utilities](./utilities) folder contains function to perform inference using Collapsed Variational Bayes (CVB) algorithm, compute Bayesian Information Criterion of the estimate, and visualize the estimates.
4. [config](./config) folder contains example configuration files compatible with this project.
5. [unit_tests](./unit_tests) folder contains a unit test for this project.

----

## Functional Sub-domains Discovery

Given the activation coordinates of 7 tasks engaging self-generated thought, the author-topic model was applied to discover 2 components fractionating the default mode network (Figure 1).

`SelfGeneratedThought/MNI152_ActivationCoordinates` contains the activation coordinates from 167 studies of self-generated thought used in our study, including the description of the input format required for our functions.

`SelfGeneratedThought/README.md` has the instructions for replicating our experiment to discover the cognitive components of self-generated thought.

----

## Co-activation Mapping

Given the activation coordinates of 323 experiments activating the left inferior frontal junction (IFJ), the author topic model was applied to revealed 3 task-dependent co-activation patterns of the IFJ (Figure 2).

For co-activation mapping of the IFJ, the author-topic model was applied in the same way as it was for discovering components of self-generated thought,
except that while there were 179 experiments of self-generated thought employing 7 behavioral tasks, each of the 323 experiments activating the IFJ was considered as employing its own unique task category.

`CoactivationMappingIFJ/README` describes the required input format for co-activation mapping meta-analysis, and instructions for replicating our experiment to estimate the co-activation patterns of the IFJ.

Please note that the activation coordinates used in our IFJ co-activation mapping experiment can only be made available after a data sharing agreement has been obtained with [BrainMap](http://brainmap.org).
We are happy to share the IFJ dataset with any user with the agreement.

----

## Configuration
At the time of release, this project was implemented with specific versions of other third-party softwares for computation and visualization, in particular:

* [FreeSurfer](https://surfer.nmr.mgh.harvard.edu/fswiki/DownloadAndInstall) 5.30,
* [FSL](https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FslInstallation) 5.0.8,
* [AFNI](https://afni.nimh.nih.gov/pub/dist/tgz/AFNI_ARCHIVE) 16.0.0
* [Workbench](https://www.humanconnectome.org/software/connectome-workbench) 1.1.1
* Matlab R2018b

Please see [CBIG repository setup instruction](https://github.com/ThomasYeoLab/CBIG/tree/master/setup) to make your local environment compatible with CBIG repository. Please see `config` folder for example configuration files.

----

## Code Release
### Download stand-alone repository

Since the whole CBIG repository is too big, we provide a stand-alone version of only this project and its dependencies. To download the stand-alone repository, visit this link:
[https://github.com/ThomasYeoLab/Standalone_Ngo2019_AuthorTopic](https://github.com/ThomasYeoLab/Standalone_Ngo2019_AuthorTopic)

### Download whole repository

Except for this project, if you want to use the code for other stable projects from our lab as well, you need to download the whole repository.

- To download the version of the code that was last tested, you can either

  - visit this link:
  [https://github.com/ThomasYeoLab/CBIG/releases/tag/v0.17.0-Fix_Absolute_Path](https://github.com/ThomasYeoLab/CBIG/releases/tag/v0.17.0-Fix_Absolute_Path)

  or

  - run the following command, if you have Git installed

  ```
  git checkout -b Ngo2019_AuthorTopic v0.17.0-Fix_Absolute_Path
  ```

----

## Updates

- Release v0.8.0 (21/01/2019): Initial release of Ngo2019 Author-Topic Model for Curated Meta-analysis project.
- Release v0.9.1 (21/02/2019): Added instruction for performing co-activation mapping experiment and references of the self-generated thought dataset.
- Release v0.10.1 (21/03/2019): Added checks for input data. Reduced runtime for unit test.
- Release v0.12.1 (09/07/2019): Update visualization function to use HCP Workbench instead of Caret.
- Release v0.15.3 (16/10/2019): Update reference.
- Release v0.17.0 (19/02/2020): Avoid using absolute paths. Add new environment variables to avoid possible problems caused by hard-coded absolute paths.

----

## Bugs and Questions

Please contact Gia at ngohoanggia@gmail.com and Thomas Yeo at yeoyeo02@gmail.com.


text:
.. include:: meta-session_set.rst

Set a session variable.

Example::

   {% button action={session_set key="foo" value="bar"} action={reload} %}

This sets the session variable "foo" to the value "bar", and then reloads the page. In your templates, you can use :ref:`model-session` to retrieve this value again::

  {{ m.session.foo }}

``key`` and ``value`` are both required values.


text:
#ifndef EXTRAFILTERSPLUGIN_H
#define EXTRAFILTERSPLUGIN_H

//! [0]
#include <QObject>
#include <QStringList>
#include <QImage>

#include <plugandpaint/interfaces.h>

class ExtraFiltersPlugin : public QObject, public FilterInterface
{
    Q_OBJECT
    Q_INTERFACES(FilterInterface)

public:
    QStringList filters() const;
    QImage filterImage(const QString &filter, const QImage &image,
                       QWidget *parent);
};
//! [0]

#endif


text:
<!--
	This example shows how to use the console.trace() function
	This function dumps a stack trace for you.
	That is the reason that this example uses recursion to show that off.
	The function does not print any messages it gets and simply disregards
	them. If you want that kind of behaviour, implement it yourself...

	References:
	The console API from firebug:
	http://getfirebug.com/wiki/index.php/Console_API

	Mark Veltzer <mark.veltzer@gmail.com>
-->
<html>
	<head>
		<script>
			// a recursive function so that we could have a nice stack trace...
			function fact(n) {
				if(n==3) {
					console.trace('this is a message','another message');
				}
				if(n==1) {
					return 1;
				} else {
					return n*fact(n-1);
				}
			}
			fact(10);
		</script>
	</head>
</html>


text:
require 'spec_helper'

describe Satisfaction do

  describe "#request_token" do

    describe "when the http response is 200 OK" do
      before :each do
        @sfn.set_consumer('key', 'secret')

        FakeWeb.register_uri(
          :get,
          "http://#{@app_host}/api/request_token",
          :body => "oauth_token=foo&oauth_token_secret=bar",
          :status => ['200']
        )
      end

      it "should be successful" do
        oauth = @sfn.request_token
        oauth.token.first.should == "foo"
        oauth.secret.first.should == "bar"
      end
    end

    describe "when the http response is 503 Service Temporarily Unavailable" do
      before(:each) do
        FakeWeb.register_uri(
          :get,
          "http://#{@app_host}/api/request_token",
          :body => "<title>maintenance</title>maintenance",
          :status => ['503']
        )
      end

      it "should raise an exception" do
        lambda {@sfn.request_token}.should raise_exception(Sfn::Error)
      end
    end
  end

end


text:
package com.google.security.zynamics.binnavi.debug.connection.helpers;

/**
 * This package contains a few helper classes for working with the debug protocol.
 */


text:
#include <stdlib.h>
#include <string>

#include "IProtocol.h"

class FelixAppProtocol : public IProtocol {
	int size_bits = 0;

public:

	FelixAppProtocol(int size_bits) : size_bits(size_bits){

	}

	int getSize_bits() { return size_bits; } ;
	int getLayer() { return LAYER_APPLICATION;};
	int getId() { return PROTOCOL_ID_FELIX_APP; };
};

#endif


text:
package com.zooz.common.client.ecomm.beans;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Created by yigalp on 25/02/2016.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class BinDetails {

    /**
     * credit card bin number attribute
     */
    @JsonProperty
    private String binNumber;

    /**
     * card type - credit/debit
     */
    @JsonProperty
    private String cardType;

    /**
     * credit card level - e.g - business card
     */
    @JsonProperty
    private String cardLevel;

    /**
     * credit card vendor name
     */
    @JsonProperty
    private String cardVendor;

    /**
     * card country code
     */
    @JsonProperty
    private String cardCountryCode;

    /**
     * card issuer name
     */
    @JsonProperty
    private String cardIssuer;

    public BinDetails() {

    }

    public String getBinNumber() {
        return binNumber;
    }

    public void setBinNumber(String binNumber) {
        this.binNumber = binNumber;
    }

    public String getCardType() {
        return cardType;
    }

    public void setCardType(String cardType) {
        this.cardType = cardType;
    }

    public String getCardLevel() {
        return cardLevel;
    }

    public void setCardLevel(String cardLevel) {
        this.cardLevel = cardLevel;
    }

    public String getCardVendor() {
        return cardVendor;
    }

    public void setCardVendor(String cardVendor) {
        this.cardVendor = cardVendor;
    }

    public String getCardCountryCode() {
        return cardCountryCode;
    }

    public void setCardCountryCode(String cardCountryCode) {
        this.cardCountryCode = cardCountryCode;
    }

    public String getCardIssuer() {
        return cardIssuer;
    }

    public void setCardIssuer(String cardIssuer) {
        this.cardIssuer = cardIssuer;
    }
}


text:
from __future__ import print_function, division
import argparse
import elasticsearch
import sqlite3
from datetime import datetime

parser = argparse.ArgumentParser(
    description='Reads and parses lobster.db. into Elasticsearch.')
parser.add_argument('directory', action='store', type=str,
                    help='Path to Lobster project folder.')

# user = 'matze'
# run = 'v29'
#
# prefix = '[' + user + '_' + run + ']'

prefix = '[template]'

es = elasticsearch.Elasticsearch([{'host': 'elk.crc.nd.edu', 'port': 9200}])

index = prefix + '_lobster_tasks'
doc_type = 'logs'

conn = sqlite3.connect(parser.parse_args().directory + 'lobster.db')
c = conn.cursor()

for row in c.execute('SELECT * FROM tasks'):
    keys = [description[0] for description in c.description]
    doc = dict(zip(keys, row))

    # parse timestamps
    doc['time_processing_end'] = datetime.fromtimestamp(
        doc['time_processing_end'])
    doc['time_prologue_end'] = datetime.fromtimestamp(doc['time_prologue_end'])
    doc['time_retrieved'] = datetime.fromtimestamp(doc['time_retrieved'])
    doc['time_stage_in_end'] = datetime.fromtimestamp(doc['time_stage_in_end'])
    doc['time_stage_out_end'] = datetime.fromtimestamp(
        doc['time_stage_out_end'])
    doc['time_transfer_in_end'] = datetime.fromtimestamp(
        doc['time_transfer_in_end'])
    doc['time_transfer_in_start'] = datetime.fromtimestamp(
        doc['time_transfer_in_start'])
    doc['time_transfer_out_end'] = datetime.fromtimestamp(
        doc['time_transfer_out_end'])
    doc['time_transfer_out_start'] = datetime.fromtimestamp(
        doc['time_transfer_out_start'])
    doc['time_wrapper_ready'] = datetime.fromtimestamp(
        doc['time_wrapper_ready'])
    doc['time_wrapper_start'] = datetime.fromtimestamp(
        doc['time_wrapper_start'])

    upsert_doc = {'doc': {'lobster_db': doc,
                          'timestamp': doc['time_retrieved']},
                  'doc_as_upsert': True}

    es.update(index=index, doc_type=doc_type, body=upsert_doc, id=doc['id'])


text:
title: Fun with FPGAs
date: 2015-12-28 20:10:49.000000000 +05:30
published: false
categories:
 - Articles
 - Tutorial
tags:
 - FPGA

excerpt: "Joting down my experiences with using an FPGA for developing systems"
---
<style>
div {
    text-align: justify;
    text-justify: inter-word;
}
</style>

{% include base_path %}

This article has been migrated from my [original post](https://embeddedinn.wordpress.com/tutorials/fun-with-fpga/){:target="_blank"}  at [embeddedinn.wordpress.com](http://embeddedinn.wordpress.com){:target="_blank"}.
{: .notice--info}

I used to play a lot with FPGAs, primarily for hardware design during my college days and the start of my career. Later on, when the embedded software industry caught my interest, I started to focus more on it  rather than hardware design. Now that I have explored both the fields to a considerable extend, I am going to club them together.

I am starting a series of articles here that will be tutorials for anyone interested in venturing to this field of hardware software co-design. I will begin off by introducing some hardware design concepts using HDLs and FPGAs and later move on to embedded system design . There we will be visiting concepts of designing hardware to run software on. I'll be using the microblaze soft-core processor as a tool to introduce that. Later on I'll illustrate how to compile and run linux on an FPGA as well as how to write drivers for custom peripherals that you design.

## Table of contents

01. HDLs and hardware design – A quick start guide
02. Creating your FPGA development setup
03. Understanding microblaze soft-core processor
04. Microblaze peripheral bus and peripherals
05. Linux on Microblaze
06. Adding a peripheral – the Linux way
07. Writing a device driver for your own peripheral


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="theme" content="hugo-academic">
  <meta name="generator" content="Hugo 0.24.1" />
  <meta name="author" content="Alvin G. Thomas">
  <meta name="description" content="Transplantation Epidemiologist">

    <link rel="stylesheet" href="/css/highlight.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha512-6MXa8B6uaO18Hid6blRMetEIoPqHf7Ux1tnyIQdpt9qI5OACx7C+O3IVTr98vwGnlcg0LOLa02i9Y1HpVhlfiw==" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.0/css/academicons.min.css" integrity="sha512-GGGNUPDhnG8LEAEDsjqYIQns+Gu8RBs4j5XGlxl7UfRaZBhCCm5jenJkeJL8uPuOXGqgl8/H1gjlWQDRjd3cUQ==" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous">

  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:400,700%7CMerriweather%7CRoboto+Mono">
  <link rel="stylesheet" href="/css/hugo-academic.css">

  <link rel="alternate" href="/index.xml" type="application/rss+xml" title="Alvin G. Thomas">
  <link rel="feed" href="/index.xml" type="application/rss+xml" title="Alvin G. Thomas">

  <link rel="icon" type="image/png" href="/img/icon.png">
  <link rel="apple-touch-icon" type="image/png" href="/img/apple-touch-icon.png">

  <link rel="canonical" href="/post/migrate-from-jekyll/">

  <title>Migrate from Jekyll to Hugo | Alvin G. Thomas</title>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
              data-target=".navbar-collapse" aria-expanded="false">
        Toggle navigation

      </button>
      Alvin G. Thomas

            Home

            Publications

            Posts

            Projects

            Teaching

            Contact

Migrate from Jekyll to Hugo

    <time datetime="2014-03-10 00:00:00 +0000 UTC" itemprop="datePublished">
      Mon, Mar 10, 2014
    </time>

    jekyll

Here are a few tips for migrating an existing website from Jekyll to Hugo. These tips can be applied in conjunction with following Hugo Academic’s getting started guide.

Move static content to static

Jekyll has a rule that any directory not starting with _ will be copied as-is to the _site output. Hugo keeps all static content under static. You should therefore move it all there.
With Jekyll, something that looked like

▾ <root>/
    ▾ images/
        logo.png

should become

▾ <root>/
    ▾ static/
        ▾ images/
            logo.png

Additionally, you’ll want any files that should reside at the root (such as CNAME) to be moved to static.

Fix content

Depending on the amount of customization that was done for each post in Jekyll, this step will require more or less effort. There are no hard and fast rules here except that hugo server --watch and the Hugo Academic example site are your friends. Test your changes and fix errors as needed.

Publish

The default is for Jekyll to publish the website to a _site directory, whereas Hugo publishes to a public directory.

A practical example

Alexandre Normand migrated his website from Jekyll to Hugo in less than a day. You can see all his changes by looking at this GitHub diff. However, bear in mind that this example is not specific to the Academic theme nor does it use the latest version of Hugo.

Writing content with Markdown, LaTeX, and Shortcodes →

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

      © 2017 Alvin G. Thomas ·

      Powered by the Academic
      theme for Hugo.


text:
<?php

namespace Ddeboer\DataImport\Tests\Reader;

use Ddeboer\DataImport\Reader\DbalReader;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Schema\Schema;

class DbalReaderTest extends \PHPUnit_Framework_TestCase
{
    public function testCalculateRowCount()
    {
        $reader = $this->getReader();

        $reader->setRowCountCalculated();
        $this->assertTrue($reader->isRowCountCalculated());

        $reader->setRowCountCalculated(false);
        $this->assertFalse($reader->isRowCountCalculated());

        $reader->setRowCountCalculated(true);
        $this->assertTrue($reader->isRowCountCalculated());
    }

    public function testGetFields()
    {
        $fields = $this->getReader()->getFields();
        $this->assertInternalType('array', $fields);
        $this->assertEquals(array('id', 'username', 'name'), $fields);
    }

    public function testCount()
    {
        $this->assertEquals(10, $this->getReader()->count());
    }

    public function testCountInhibited()
    {
        $reader = $this->getReader();
        $reader->setRowCountCalculated(false);

        $this->assertEquals(null, $reader->count());
    }

    public function testSqlAndParamsAreMutable()
    {
        $reader = $this->getReader();

        $reader->setSql('SELECT * FROM groups WHERE id = :id', array('id' => 2));
        $this->assertAttributeEquals('SELECT * FROM groups WHERE id = :id', 'sql', $reader);
        $this->assertAttributeEquals(array('id' => 2), 'params', $reader);
    }

    public function testChangeSqlOrParamsClearsNumRowsAndStatement()
    {
        $reader = $this->getReader();
        $reader->count();
        $reader->getFields();

        $this->assertAttributeNotEmpty('rowCount', $reader);
        $this->assertAttributeNotEmpty('stmt', $reader);

        $reader->setSql('SELECT * FROM `user` WHERE id IN (:id)', array('id' => array()));

        $this->assertAttributeEmpty('rowCount', $reader);
        $this->assertAttributeEmpty('stmt', $reader);
    }

    public function testIterate()
    {
        $i=31;
        foreach ($this->getReader() as $key => $row) {
            $this->assertInternalType('array', $row);
            $this->assertEquals('user-'.$i, $row['username']);
            $this->assertEquals($i - 31, $key);
            $i++;
        }

        $this->assertEquals(41, $i);
    }

    public function testReaderRewindWorksCorrectly()
    {
        $reader = $this->getReader();
        foreach ($reader as $row) {
            if (!isset($row['username'])) {
                $this->fail('There should be a username');
            }
            if ($row['username'] == 'user-35') {
                break;
            }
        }

        $reader->rewind();

        $this->assertEquals(array(
            'id' => 31,
            'username' => 'user-31',
            'name' => 'name 4',
        ), $reader->current());
    }

    public function testCallingCurrentTwiceShouldNotAdvance()
    {
        $reader = $this->getReader();

        $expected = array(
            'id' => 31,
            'username' => 'user-31',
            'name' => 'name 4',
        );
        $this->assertEquals($expected, $reader->current());
        $this->assertEquals($expected, $reader->current());
    }

    public function testEmptyResultDoesNotThrowException()
    {
        $reader = $this->getReader();

        $reader->setSql(null, array('name' => 'unknown group'));
        $this->assertInternalType('array', $reader->getFields());
    }

    public function testCallValidRewindsIfNeeded()
    {
        $reader = $this->getReader();

        $this->assertTrue($reader->valid());
        $this->assertAttributeInternalType('array', 'data', $reader);
    }

    public function getConnection()
    {
        $params = array(
            'driver' => 'pdo_sqlite',
            'memory' => true,
        );

        $connection = DriverManager::getConnection($params, new Configuration());

        $schema = new Schema();

        $table = $schema->createTable('groups');
        $table->addColumn('id', 'integer', ['autoincrement' => true]);
        $table->addColumn('name', 'string', array('length' => 45));
        $table->setPrimaryKey(array('id'));

        $myTable = $schema->createTable('user');
        $myTable->addColumn('id', 'integer', array('unsigned' => true, 'autoincrement' => true));
        $myTable->addColumn('username', 'string', array('length' => 32));
        $myTable->addColumn('group_id', 'integer');
        $myTable->setPrimaryKey(array('id'));
        $myTable->addUniqueIndex(array('username'));
        $myTable->addForeignKeyConstraint($table, array('group_id'), array('id'));

        foreach ($schema->toSql(new SqlitePlatform()) as $query) {
            $connection->query($query);
        };

        return $connection;
    }

    protected function getReader()
    {
        $connection = $this->getConnection();
        $this->loadFixtures($connection);

        return new DbalReader($connection, implode(' ', array(
            'SELECT u.id, u.username, g.name',
            'FROM `user` u INNER JOIN groups g ON u.group_id = g.id',
            'WHERE g.name LIKE :name',
        )), array(
            'name' => 'name 4',
        ));
    }

    /**
     * @param Connection $connection
     */
    protected function loadFixtures($connection)
    {
        $counter = 1;
        for ($i = 1; $i <= 10; $i++) {
            $connection->insert('groups', array('name' => "name {$i}"));
            $id = $connection->lastInsertId();

            for ($j = 1; $j <= 10; $j++) {
                $connection->insert('user', array(
                    'username' => "user-{$counter}",
                    'group_id' => $id,
                ));

                $counter++;
            }
        }
    }
}


text:
'use strict';

var angular = require('angular/index-browserify.js');
module.exports = function($resource, GOOGLE_API_KEY){

  var urlTemplate =
    "https://www.googleapis.com/youtube/v3/channels?" +
    "part=id,snippet,contentDetails,brandingSettings,statistics,status&" +
    "id=:showId&" +
    "key=:apiKey";

  var Show = $resource(urlTemplate, {apiKey: GOOGLE_API_KEY});
  angular.extend(Show.prototype, {

    getId: function () {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].id;
    },

    getTitle: function () {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].snippet.title;
    },

    getDescription: function () {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].snippet.description;
    },

    getThumbnailUrl: function (key) {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].snippet.thumbnails[key].url;
    },

    getBannerImageUrl: function () {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].brandingSettings.image.bannerImageUrl;
    },

    getViewCount: function () {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].statistics.viewCount;
    },

    getCommentCount: function () {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].statistics.commentCount;
    },

    getSubscriberCount: function () {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].statistics.subscriberCount;
    },

    getVideoCount: function () {
      if (typeof this.items === 'undefined') { return ''; }
      return this.items[0].statistics.videoCount;
    }

  });
  return Show;
};


text:
package main

import (
	"fmt"

	"github.com/tve/devices/sx1231"
	"github.com/tve/devices/varint"
)

//===== JeeLabs rfm69 ACK protocol

const group = 6 // FIXME: this needs to come from config!

// jlAck takes a raw rfm69 packet using the JeeLabs format, looks whether it
// requests an ack and if so publishes one. The ACK contains the node ID as dest, the GW ID
// as source, a byte with the RX SNR (0..63), and a byte with the FEI/128.
// The SNR is the difference between the received RSSI and the RSSI threshold
// configured into the radio (the driver adjusts this threshold dynamically).
// The top 2 bits of the rssi byte are effectively unused.
// TODO: if the RX RSSI wasn't measured it redults in a 0 SNR, we should omit the two
// ACK payload bytes instead.
func jlAck(m *RawRxMessage, pub pubFunc, debug LogPrintf) {
	src, _, ack, payload, err := sx1231.JLDecode(group, m.Payload.Packet)
	if err != nil {
		debug("Can't decode JL packet: %s", err)
		return
	}
	if !ack {
		debug("no ACK needed")
		return // no ack requested
	}
	// Send an ack back.
	debug("ACK reply to node %d!", src)
	ackPkt := sx1231.MakeJLAck(group, payload)
	snr := m.Payload.Snr
	switch {
	case snr < 0:
		snr = 0
	case snr > 63:
		snr = 63
	}
	ackPkt = append(ackPkt, byte(snr), byte(m.Payload.Fei/128))
	txPkt := RawTxPacket{Packet: ackPkt}
	pub("", txPkt)
}

func init() {
	RegisterModule(module{"jl-ack", jlAck})
}

//===== JeeLabs rfm69 packet decoder

// jlDecode decodes a packet using the JeeLabs protocol and having a type byte as the first byte in
// the payload. It publishes to a topic by adding "/<type>" to the configured publication topic.
// This is intended to allow further decoding by having modules subscribe to their packet type.
// The format of the packet published to MQTT is described by the jlRxPacket struct.
func jlDecode(m *RawRxMessage, pub pubFunc, debug LogPrintf) {
	src, dst, ack, payload, err := sx1231.JLDecode(group, m.Payload.Packet)
	if err != nil {
		debug("Can't decode JL packet: %s", err)
		return
	}
	if len(payload) < 1 {
		return
	}
	txPkt := jlRxPacket{RawRxPacket: m.Payload, Src: src, Dst: dst, Ack: ack, Type: payload[0]}
	txPkt.Packet = payload[1:]
	topic := fmt.Sprintf("/%d", txPkt.Type)
	pub(topic, txPkt)
}

func init() {
	RegisterModule(module{"jl-decode", jlDecode})
}

// jlRxPacket is the structure of the packets published to MQTT by the jl-decode module.
type jlRxPacket struct {
	RawRxPacket
	Src  byte `json:"src"`
	Dst  byte `json:"dst"`
	Ack  bool `json:"ack"`
	Type byte `json:"type"`
}

type jlRxMessage struct {
	Topic   string
	Payload jlRxPacket
}

//===== JeeLabs rfm69 varint decoder

// jlviDecode decodes varints in the payload of a packet. It expects a decoded packet whose
// paylaod consists entirely of varints.
func jlviDecode(m *jlRxMessage, pub pubFunc, debug LogPrintf) {
	pub("", varintRxPacket{jlRxPacket: m.Payload, Data: varint.Decode(m.Payload.Packet)})
}

func init() {
	RegisterModule(module{"jl-varint", jlviDecode})
}

// varintRxPacket is the structure of packets published to MQTT by the jl-varint decoder.
type varintRxPacket struct {
	jlRxPacket
	Data []int `json:"data"`
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;

namespace Foundation.Build.VisualBasic6
{
    public class VB6ProjectReader
    {
        /// <summary>
        /// Reads all the project values from the specified Visual Basic 6 project file.
        /// </summary>
        /// <param name="fileName">The VB6 project fileName.</param>
        /// <returns></returns>
        public VB6ProjectProperties Read(string fileName)
        {
            if (fileName == null) throw new ArgumentNullException("fileName");
            if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentException("The project fileName must not be empty.", "fileName");

            var projectFile = new FileInfo(fileName);

            if (!projectFile.Exists) throw new FileNotFoundException("Couldn't find project file.", projectFile.FullName);

            // Read in all the lines
            var lines = File.ReadAllLines(projectFile.FullName)
                .Where(s => !string.IsNullOrWhiteSpace(s) && s.Contains("="));

            var results = new Dictionary<string, IList<string>>();

            foreach (var line in lines)
            {
                // Split the key and value
                string[] keyAndValue = line.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                Debug.Assert(keyAndValue.Length == 2, "Key and value not split correctly", "Project line: {0}", line);
                string key = keyAndValue[0].ToLower(CultureInfo.InvariantCulture);
                string value = keyAndValue[1].Replace("\"", "").Trim();

                // Are there any existing entries for this key?
                IList<string> valueCollection;

                if (!results.TryGetValue(key, out valueCollection))
                {
                    // There are no entries for this key so we'll have to initialize it first
                    valueCollection = new List<string>();
                }

                valueCollection.Add(value);

                results[key] = valueCollection;
            }

            return new VB6ProjectProperties(results);
        }

        public VB6Project Parse(string fileName)
        {
            var values = Read(fileName);
            var project = new VB6Project
                              {
                                  FileName = fileName,
                                  Name = values.GetSingleValue("Name"),
                                  ProjectType =
                                      (VB6ProjectType)
                                      Enum.Parse(typeof (VB6ProjectType), values.GetSingleValue("Type")),
                                  Startup = values.GetSingleValue("Startup"),
                                  IconForm = values.GetSingleValue("IconForm"),
                                  CompatibilityFile = values.GetSingleValue("CompatibleEXE32"),
                                  CompatibilityMode = values.GetSingleValue("CompatibleMode"),
                                  ResourceFile = values.GetSingleValue("ResFile32")
                              };

            // Parse in the source files
            var sourceFiles = ParseSourceItems(values.GetValues("Form"), VB6SourceFileType.Form)
                .Concat(ParseSourceItems(values.GetValues("Module"), VB6SourceFileType.Module))
                .Concat(ParseSourceItems(values.GetValues("Class"), VB6SourceFileType.Class));
            foreach (var sourceFile in sourceFiles) project.SourceFiles.Add(sourceFile);

            // References & Components
            var references = values.GetValues("Reference").Select(ParseReference);
            var components = values.GetValues("Object").Select(ParseReference);

            foreach (var component in components) project.Components.Add(component);
            foreach (var reference in references) project.References.Add(reference);

            return project;
        }

        private IEnumerable<VB6SourceFile> ParseSourceItems(IEnumerable<string> names, VB6SourceFileType sourceFileType)
        {
            if (names == null) return Enumerable.Empty<VB6SourceFile>();
            return names.Select(s => ParseSourceItem(s, sourceFileType));
        }

        private VB6SourceFile ParseSourceItem(string name, VB6SourceFileType sourceFileType)
        {
            var result = new VB6SourceFile();

            // If the name is in two parts split by a semi-colon or comma, that is the name and fileName
            var parts = name.Split(new[] {";", ","}, StringSplitOptions.RemoveEmptyEntries);

            result.Type = sourceFileType;

            switch (parts.Length)
            {
                case 1:
                    result.Name = Path.GetFileNameWithoutExtension(parts[0]);
                    result.FileName = parts[0];
                    break;
                case 2:
                    result.Name = parts[0];
                    result.FileName = parts[1];
                    break;
                default:
                    throw new ArgumentException("The source item name has too many parts (expecting 1 or 2 parts). Name: " + name, "name");
            }

            return result;
        }

        public static VB6Reference ParseReference(string reference)
        {
            // Split the reference into its parts, delimited by #
            // 0 = GUID
            // 1 = Version
            // 2 = Not sure. Usually 0 and doesn't seem to mean anything.
            // 3 = Path and fileName
            // 4 = Name (optional)
            string[] parts = GetReferenceParts(reference).ToArray();

            var guidString = parts[0];

            if (guidString.StartsWith("*")) guidString = guidString.Substring(3);
            var guid = new Guid(guidString);
            string version = parts[1];
            string filename = parts[3];

            string description = parts.Length > 4 ? parts[4] : Path.GetFileNameWithoutExtension(filename);

            return new VB6Reference(guid, version, filename, description);
        }

        private static IEnumerable<string> GetReferenceParts(string reference)
        {
            return reference.Trim()
                .Split(new[] { '#', ';' }, StringSplitOptions.None)
                .Select(s => s.Trim())
                .ToArray();
        }
    }
}


text:
package org.datavec.spark.transform;

/**
 * Created by kepricon on 17. 6. 20.
 */
public enum TransformDataType {
    CSV, IMAGE,
}


text:
Action Generator

This generator helps you to quickly generate the skeleton code for a new action class.

<?php $form=$this->beginWidget('CCodeForm', array('model'=>$model)); ?>

    <?php echo $form->labelEx($model,'baseClass'); ?>
    <?php echo $form->dropDownList($model,'baseClass',$model->getBaseClassNames(),array('style'=>'width:100%;')); ?>

        This is the class that the new behavior class will extend from.
        Please make sure the class exists and can be autoloaded.

    <?php echo $form->error($model,'baseClass'); ?>

<?php
$this->widget('zii.widgets.jui.CJuiTabs', array(
    'tabs'=>array(
        'Component'=>array(
            'content' => $this->renderPartial('__class',array('model'=>$model,'form'=>$form),true),
            'id' => 'tab1'),
        'Information'=>array(
            'content' => $this->renderPartial('__infos',null,true),
            'id' => 'tab2'),
    ),
    'headerTemplate'=>'
{title}
',
    'options'=>array(
        'collapsible'=>true,
    ),
    'htmlOptions'=>array(
        'style'=>'width:100%;'
    ),
));
?>
<?php $this->endWidget(); ?>


text: Heliosphere's educational project based on technology experimentations.


text:
package alluxio.wire;

import com.google.common.base.Objects;

import javax.annotation.concurrent.NotThreadSafe;

/**
 * Class that represents the available, free, and total capacity.
 */
@NotThreadSafe
public class Capacity {
  private long mTotal;
  private long mUsed;

  /**
   * Creates a new instance of {@link Capacity}.
   */
  public Capacity() {}

  /**
   * @return the total capacity
   */
  public long getTotal() {
    return mTotal;
  }

  /**
   * @return the used capacity
   */
  public long getUsed() {
    return mUsed;
  }

  /**
   * @param total the total capacity to use
   * @return the capacity
   */
  public Capacity setTotal(long total) {
    mTotal = total;
    return this;
  }

  /**
   * @param used the used capacity to use
   * @return the capacity
   */
  public Capacity setUsed(long used) {
    mUsed = used;
    return this;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof Capacity)) {
      return false;
    }
    Capacity that = (Capacity) o;
    return mTotal == that.mTotal && mUsed == that.mUsed;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(mTotal, mUsed);
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(this).add("total", mTotal).add("used", mUsed).toString();
  }
}