Example usage for java.util Locale equals

List of usage examples for java.util Locale equals

Introduction

In this page you can find the example usage for java.util Locale equals.

Prototype

@Override
public boolean equals(Object obj) 

Source Link

Document

Returns true if this Locale is equal to another object.

Usage

From source file:org.wings.session.Session.java

void determineLocale() {
    if (supportedLocales == null) {
        setLocale(servletRequest.getLocale());
    }/*  w  w w  . j  ava 2 s. c  o m*/

    Enumeration<Locale> requestedLocales = servletRequest.getLocales();
    if (supportedLocales != null) {
        while (requestedLocales.hasMoreElements()) {
            Locale locale = requestedLocales.nextElement();
            for (int i = 0; i < supportedLocales.length; i++) {
                Locale supportedLocale = supportedLocales[i];
                if (locale.equals(supportedLocale)) {
                    setLocale(supportedLocale);
                    return;
                }
            }
        }
        log.warn(buildLocaleNotSupportedMessage(servletRequest));
        setLocale(supportedLocales[0]);
    } else {
        setLocale(requestedLocales.nextElement());
    }
}

From source file:org.opencms.i18n.tools.CmsContainerPageCopier.java

/**
 * Starts the page copying process.<p>
 *
 * @param source the source (can be either a container page, or a folder whose default file is a container page)
 * @param target the target folder//from   w w w .  ja  v a 2s . c  o  m
 * @param targetName the name to give the new folder
 *
 * @throws CmsException if soemthing goes wrong
 * @throws NoCustomReplacementException if a custom replacement element was not found
 */
public void run(CmsResource source, CmsResource target, String targetName)
        throws CmsException, NoCustomReplacementException {

    LOG.info("Starting page copy process: page='" + source.getRootPath() + "', targetFolder='"
            + target.getRootPath() + "'");
    CmsObject rootCms = OpenCms.initCmsObject(m_cms);
    rootCms.getRequestContext().setSiteRoot("");
    if (m_copyMode == CopyMode.automatic) {
        Locale sourceLocale = OpenCms.getLocaleManager().getDefaultLocale(rootCms, source);
        Locale targetLocale = OpenCms.getLocaleManager().getDefaultLocale(rootCms, target);
        // if same locale, copy elements, otherwise use configured setting
        LOG.debug("copy mode automatic: source=" + sourceLocale + " target=" + targetLocale + " reuseConfig="
                + OpenCms.getLocaleManager().shouldReuseElements() + "");
        if (sourceLocale.equals(targetLocale)) {
            m_copyMode = CopyMode.smartCopyAndChangeLocale;
        } else {
            if (OpenCms.getLocaleManager().shouldReuseElements()) {
                m_copyMode = CopyMode.reuse;
            } else {
                m_copyMode = CopyMode.smartCopyAndChangeLocale;
            }
        }
    }

    if (source.isFolder()) {
        if (source.equals(target)) {
            throw new CmsException(Messages.get().container(Messages.ERR_PAGECOPY_SOURCE_IS_TARGET_0));
        }
        CmsResource page = m_cms.readDefaultFile(source, CmsResourceFilter.IGNORE_EXPIRATION);
        if ((page == null) || !CmsResourceTypeXmlContainerPage.isContainerPage(page)) {
            throw new CmsException(Messages.get().container(Messages.ERR_PAGECOPY_INVALID_PAGE_0));
        }
        List<CmsProperty> properties = Lists.newArrayList(m_cms.readPropertyObjects(source, false));
        Iterator<CmsProperty> iterator = properties.iterator();
        while (iterator.hasNext()) {
            CmsProperty prop = iterator.next();
            // copied folder may be root of a locale subtree, but since we may want to copy to a different locale,
            // we don't want the locale property in the copy
            if (prop.getName().equals(CmsPropertyDefinition.PROPERTY_LOCALE)
                    || prop.getName().equals(CmsPropertyDefinition.PROPERTY_ELEMENT_REPLACEMENTS)) {
                iterator.remove();
            }
        }

        I_CmsFileNameGenerator nameGen = OpenCms.getResourceManager().getNameGenerator();
        String copyPath;
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(targetName)) {
            copyPath = CmsStringUtil.joinPaths(target.getRootPath(), targetName);
            if (rootCms.existsResource(copyPath)) {
                copyPath = nameGen.getNewFileName(rootCms, copyPath + "%(number)", 4, true);
            }
        } else {
            copyPath = CmsFileUtil
                    .removeTrailingSeparator(CmsStringUtil.joinPaths(target.getRootPath(), source.getName()));
            copyPath = nameGen.getNewFileName(rootCms, copyPath + "%(number)", 4, true);
        }
        Double maxNavPosObj = readMaxNavPos(target);
        double maxNavpos = maxNavPosObj == null ? 0 : maxNavPosObj.doubleValue();
        boolean hasNavpos = maxNavPosObj != null;
        CmsResource copiedFolder = rootCms.createResource(copyPath,
                OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolder.RESOURCE_TYPE_NAME), null,
                properties);
        m_createdResources.add(copiedFolder);
        if (hasNavpos) {
            String newNavPosStr = "" + (maxNavpos + 10);
            rootCms.writePropertyObject(copiedFolder.getRootPath(),
                    new CmsProperty(CmsPropertyDefinition.PROPERTY_NAVPOS, newNavPosStr, null));
        }
        String pageCopyPath = CmsStringUtil.joinPaths(copiedFolder.getRootPath(), page.getName());
        m_originalPage = page;
        m_targetFolder = target;
        m_copiedFolderOrPage = copiedFolder;
        rootCms.copyResource(page.getRootPath(), pageCopyPath);

        CmsResource copiedPage = rootCms.readResource(pageCopyPath, CmsResourceFilter.IGNORE_EXPIRATION);

        m_createdResources.add(copiedPage);
        replaceElements(copiedPage);
        CmsLocaleGroupService localeGroupService = rootCms.getLocaleGroupService();
        if (Status.linkable == localeGroupService.checkLinkable(m_originalPage, copiedPage)) {
            try {
                localeGroupService.attachLocaleGroupIndirect(m_originalPage, copiedPage);
            } catch (CmsException e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
        tryUnlock(copiedFolder);
    } else {
        CmsResource page = source;
        if (!CmsResourceTypeXmlContainerPage.isContainerPage(page)) {
            throw new CmsException(Messages.get().container(Messages.ERR_PAGECOPY_INVALID_PAGE_0));
        }
        I_CmsFileNameGenerator nameGen = OpenCms.getResourceManager().getNameGenerator();
        String copyPath = CmsFileUtil
                .removeTrailingSeparator(CmsStringUtil.joinPaths(target.getRootPath(), source.getName()));
        int lastDot = copyPath.lastIndexOf(".");
        int lastSlash = copyPath.lastIndexOf("/");
        if (lastDot > lastSlash) { // path has an extension
            String macroPath = copyPath.substring(0, lastDot) + "%(number)" + copyPath.substring(lastDot);
            copyPath = nameGen.getNewFileName(rootCms, macroPath, 4, true);
        } else {
            copyPath = nameGen.getNewFileName(rootCms, copyPath + "%(number)", 4, true);
        }
        Double maxNavPosObj = readMaxNavPos(target);
        double maxNavpos = maxNavPosObj == null ? 0 : maxNavPosObj.doubleValue();
        boolean hasNavpos = maxNavPosObj != null;
        rootCms.copyResource(page.getRootPath(), copyPath);
        if (hasNavpos) {
            String newNavPosStr = "" + (maxNavpos + 10);
            rootCms.writePropertyObject(copyPath,
                    new CmsProperty(CmsPropertyDefinition.PROPERTY_NAVPOS, newNavPosStr, null));
        }
        CmsResource copiedPage = rootCms.readResource(copyPath);
        m_createdResources.add(copiedPage);
        m_originalPage = page;
        m_targetFolder = target;
        m_copiedFolderOrPage = copiedPage;
        replaceElements(copiedPage);
        CmsLocaleGroupService localeGroupService = rootCms.getLocaleGroupService();
        if (Status.linkable == localeGroupService.checkLinkable(m_originalPage, copiedPage)) {
            try {
                localeGroupService.attachLocaleGroupIndirect(m_originalPage, copiedPage);
            } catch (CmsException e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
        tryUnlock(copiedPage);

    }
}

From source file:org.parancoe.web.util.ReloadableResourceBundleMessageSource.java

/**
 * Calculate all filenames for the given bundle basename and Locale. Will calculate filenames
 * for the given Locale, the system Locale (if applicable), and the default file.
 *
 * @param basename the basename of the bundle
 * @param locale the locale//from   w w  w  .  j a  v a2  s .co m
 * @return the List of filenames to check
 * @see #setFallbackToSystemLocale
 * @see #calculateFilenamesForLocale
 */
protected List<String> calculateAllFilenames(String basename, Locale locale) {
    synchronized (this.cachedFilenames) {
        Map<Locale, List<String>> localeMap = this.cachedFilenames.get(basename);
        if (localeMap != null) {
            List<String> filenames = localeMap.get(locale);
            if (filenames != null) {
                return filenames;
            }
        }
        List<String> filenames = new ArrayList<String>(7);
        filenames.addAll(calculateFilenamesForLocale(basename, locale));
        if (this.fallbackToSystemLocale && !locale.equals(Locale.getDefault())) {
            List<String> fallbackFilenames = calculateFilenamesForLocale(basename, Locale.getDefault());
            for (String fallbackFilename : fallbackFilenames) {
                if (!filenames.contains(fallbackFilename)) {
                    // Entry for fallback locale that isn't already in filenames list.
                    filenames.add(fallbackFilename);
                }
            }
        }
        filenames.add(basename);
        if (localeMap != null) {
            localeMap.put(locale, filenames);
        } else {
            localeMap = new HashMap<Locale, List<String>>();
            localeMap.put(locale, filenames);
            this.cachedFilenames.put(basename, localeMap);
        }
        return filenames;
    }
}

From source file:net.e_fas.oss.tabijiman.MapsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    e_print("onCreate");

    // ActionBar?
    if (savedInstanceState == null) {
        // customActionBar??
        View customActionBarView = this.getActionBarView();

        // ActionBar??
        ActionBar actionBar = this.getSupportActionBar();

        // ?????('<' <- ???)
        if (actionBar != null) {

            // ???????
            actionBar.setDisplayShowTitleEnabled(false);

            // icon???????
            actionBar.setDisplayShowHomeEnabled(false);

            // ActionBar?customView?
            actionBar.setCustomView(customActionBarView);

            // CutomView??
            actionBar.setDisplayShowCustomEnabled(true);
        }/*from   www  .j av  a  2  s  . c  om*/
    }

    // ?????
    Locale locale = Locale.getDefault();
    if (locale.equals(Locale.JAPAN) || locale.equals(Locale.JAPANESE)) {
        locale = Locale.JAPAN;
    } else {
        locale = Locale.ENGLISH;
    }

    // ??
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    // Resources??
    config.locale = locale;
    Resources resources = getBaseContext().getResources();
    // Resources??????
    resources.updateConfiguration(config, null);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    try {
        new CreateInitData(this).exec(locale);
        new SPARQL().query(AppSetting.query_place, "place");
        new SPARQL().query(AppSetting.query_frame, "frame");
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }

    makeTempDir();

    // ???
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo == null) {
        Toast.makeText(getApplicationContext(),
                "???????????",
                Toast.LENGTH_LONG).show();
    }

    buttons = new ArrayList<>();

    View.OnClickListener change_button = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            CameraPosition cameraPos;

            if (v == TrainButton) {

                zoomLevel = 9.0f;

                cameraPos = new CameraPosition.Builder()
                        .target(new LatLng(nowLocation.latitude, nowLocation.longitude)).zoom(zoomLevel)
                        .bearing(0).build();
            } else if (v == CarButton) {

                zoomLevel = 11.0f;

                cameraPos = new CameraPosition.Builder()
                        .target(new LatLng(nowLocation.latitude, nowLocation.longitude)).zoom(zoomLevel)
                        .bearing(0).build();
            } else {

                zoomLevel = 14.0f;

                cameraPos = new CameraPosition.Builder()
                        .target(new LatLng(nowLocation.latitude, nowLocation.longitude)).zoom(zoomLevel)
                        .bearing(0).build();
            }

            if (!v.isActivated()) {

                v.setActivated(true);

                for (int i = 0; i < buttons.size(); i++) {

                    if (buttons.get(i) != v) {
                        buttons.get(i).setActivated(false);
                    }
                }
            }

            mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPos));
        }
    };

    View.OnClickListener marker_change_button = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!v.isActivated()) {

                v.setActivated(true);
                if (v == FrameSwitch) {

                    setMarker("frame");

                    FrameMarkerOptions.clear();
                } else {

                    setMarker("place");

                    PlaceMarkerOptions.clear();
                }
            } else {

                v.setActivated(false);
                if (v == FrameSwitch) {

                    for (Marker m : FrameMarker) {
                        m.remove();
                    }

                    FrameMarker.clear();
                } else {
                    for (Marker m : PlaceMarker) {
                        m.remove();
                    }

                    PlaceMarker.clear();
                }
            }
        }
    };

    // LocationManager?
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    TakePicture = (ImageButton) findViewById(R.id.takePicture);
    TakePicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent TakePictureView = new Intent(getApplicationContext(), TakePicture.class);
            startActivity(TakePictureView);
        }
    });

    TrainButton = (ImageButton) findViewById(R.id.Train);
    TrainButton.setActivated(false);
    TrainButton.setOnClickListener(change_button);

    CarButton = (ImageButton) findViewById(R.id.Car);
    CarButton.setActivated(true);
    CarButton.setOnClickListener(change_button);

    WalkButton = (ImageButton) findViewById(R.id.Walk);
    WalkButton.setActivated(false);
    WalkButton.setOnClickListener(change_button);

    buttons = Arrays.asList(TrainButton, CarButton, WalkButton);

    FrameSwitch = (ImageButton) findViewById(R.id.showFrame);
    FrameSwitch.setActivated(true);
    FrameSwitch.setOnClickListener(marker_change_button);

    PlaceSwitch = (ImageButton) findViewById(R.id.showPlace);
    PlaceSwitch.setActivated(true);
    PlaceSwitch.setOnClickListener(marker_change_button);

    GoFukuiButton = (ImageButton) findViewById(R.id.GoFukuiButton);

    //        new AppSetting(this);
    //        AppSetting.context = getApplicationContext();
    AppSetting.Inc_CountRun();
    e_print("Run_Count >> " + AppSetting.CountRun());

    if (AppSetting.CountRun() % 20 == 0) {
        GoFukuiButton.setVisibility(View.VISIBLE);
    }

    FrameCollectionButton = (ImageButton) findViewById(R.id.frameCollection);
    FrameCollectionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent collection = new Intent(getApplicationContext(), FrameCollection.class);
            startActivity(collection);
        }
    });

    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    //        mapFragment.getMap();

    helper = new SQLiteHelper(this);
    db = helper.getWritableDatabase();

}

From source file:com.application.utils.FastDateParser.java

/**
 * <p>Constructs a new FastDateParser.</p>
 *
 * @param pattern      non-null {@link java.text.SimpleDateFormat} compatible
 *                     pattern/* w  ww .  ja v a2  s.co m*/
 * @param timeZone     non-null time zone to use
 * @param locale       non-null locale
 * @param centuryStart The start of the century for 2 digit year parsing
 * @since 3.3
 */
protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale,
        final Date centuryStart) {
    this.pattern = pattern;
    this.timeZone = timeZone;
    this.locale = locale;

    final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);
    int centuryStartYear;
    if (centuryStart != null) {
        definingCalendar.setTime(centuryStart);
        centuryStartYear = definingCalendar.get(Calendar.YEAR);
    } else if (locale.equals(JAPANESE_IMPERIAL)) {
        centuryStartYear = 0;
    } else {
        // from 80 years ago to 20 years from now
        definingCalendar.setTime(new Date());
        centuryStartYear = definingCalendar.get(Calendar.YEAR) - 80;
    }
    century = centuryStartYear / 100 * 100;
    startYear = centuryStartYear - century;

    init(definingCalendar);
}

From source file:com.xpn.xwiki.test.MockitoOldcore.java

public void before(Class<?> testClass) throws Exception {
    // Statically store the component manager in {@link Utils} to be able to access it without
    // the context.
    Utils.setComponentManager(getMocker());

    this.context = new XWikiContext();

    getXWikiContext().setWikiId("xwiki");
    getXWikiContext().setMainXWiki("xwiki");

    this.spyXWiki = spy(new XWiki());
    getXWikiContext().setWiki(this.spyXWiki);

    this.mockHibernateStore = mock(XWikiHibernateStore.class);
    this.mockVersioningStore = mock(XWikiVersioningStoreInterface.class);
    this.mockRightService = mock(XWikiRightService.class);
    this.mockGroupService = mock(XWikiGroupService.class);

    doReturn(this.mockHibernateStore).when(this.spyXWiki).getStore();
    doReturn(this.mockHibernateStore).when(this.spyXWiki).getHibernateStore();
    doReturn(this.mockVersioningStore).when(this.spyXWiki).getVersioningStore();
    doReturn(this.mockRightService).when(this.spyXWiki).getRightService();
    doReturn(this.mockGroupService).when(this.spyXWiki).getGroupService(getXWikiContext());

    // We need to initialize the Component Manager so that the components can be looked up
    getXWikiContext().put(ComponentManager.class.getName(), getMocker());

    if (testClass.getAnnotation(AllComponents.class) != null) {
        // If @AllComponents is enabled force mocking AuthorizationManager and ContextualAuthorizationManager if not
        // already mocked
        this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class, false);
        this.mockContextualAuthorizationManager = getMocker()
                .registerMockComponent(ContextualAuthorizationManager.class, false);
    } else {/*from www.  j  av  a  2 s. co  m*/
        // Make sure an AuthorizationManager and a ContextualAuthorizationManager is available
        if (!getMocker().hasComponent(AuthorizationManager.class)) {
            this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class);
        }
        if (!getMocker().hasComponent(ContextualAuthorizationManager.class)) {
            this.mockContextualAuthorizationManager = getMocker()
                    .registerMockComponent(ContextualAuthorizationManager.class);
        }
    }

    // Make sure a default ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class)) {
        this.configurationSource = getMocker().registerMemoryConfigurationSource();
    }

    // Make sure a "xwikicfg" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT)) {
        this.xwikicfgConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(
                MockConfigurationSource.getDescriptor(XWikiCfgConfigurationSource.ROLEHINT),
                this.xwikicfgConfigurationSource);
    }
    // Make sure a "wiki" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "wiki")) {
        this.wikiConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("wiki"),
                this.wikiConfigurationSource);
    }

    // Make sure a "space" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "space")) {
        this.spaceConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("space"),
                this.spaceConfigurationSource);
    }

    // Since the oldcore module draws the Servlet Environment in its dependencies we need to ensure it's set up
    // correctly with a Servlet Context.
    if (getMocker().hasComponent(Environment.class)
            && getMocker().getInstance(Environment.class) instanceof ServletEnvironment) {
        ServletEnvironment environment = getMocker().getInstance(Environment.class);

        ServletContext servletContextMock = mock(ServletContext.class);
        environment.setServletContext(servletContextMock);
        when(servletContextMock.getAttribute("javax.servlet.context.tempdir"))
                .thenReturn(new File(System.getProperty("java.io.tmpdir")));

        File testDirectory = new File("target/test-" + new Date().getTime());
        this.temporaryDirectory = new File(testDirectory, "temporary-dir");
        this.permanentDirectory = new File(testDirectory, "permanent-dir");
        environment.setTemporaryDirectory(this.temporaryDirectory);
        environment.setPermanentDirectory(this.permanentDirectory);
    }

    // Initialize the Execution Context
    if (this.componentManager.hasComponent(ExecutionContextManager.class)) {
        ExecutionContextManager ecm = this.componentManager.getInstance(ExecutionContextManager.class);
        ExecutionContext ec = new ExecutionContext();
        ecm.initialize(ec);
    }

    // Bridge with old XWiki Context, required for old code.
    Execution execution;
    if (this.componentManager.hasComponent(Execution.class)) {
        execution = this.componentManager.getInstance(Execution.class);
    } else {
        execution = this.componentManager.registerMockComponent(Execution.class);
    }
    ExecutionContext econtext;
    if (MockUtil.isMock(execution)) {
        econtext = new ExecutionContext();
        when(execution.getContext()).thenReturn(econtext);
    } else {
        econtext = execution.getContext();
    }

    // Set a few standard things in the ExecutionContext
    econtext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, this.context);
    this.scriptContext = (ScriptContext) econtext
            .getProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID);
    if (this.scriptContext == null) {
        this.scriptContext = new SimpleScriptContext();
        econtext.setProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID, this.scriptContext);
    }

    if (!this.componentManager.hasComponent(ScriptContextManager.class)) {
        ScriptContextManager scriptContextManager = this.componentManager
                .registerMockComponent(ScriptContextManager.class);
        when(scriptContextManager.getCurrentScriptContext()).thenReturn(this.scriptContext);
        when(scriptContextManager.getScriptContext()).thenReturn(this.scriptContext);
    }

    // Initialize XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER)) {
        Provider<XWikiContext> xcontextProvider = this.componentManager
                .registerMockComponent(XWikiContext.TYPE_PROVIDER);
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }

    // Initialize readonly XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER, "readonly")) {
        Provider<XWikiContext> xcontextProvider = this.componentManager
                .registerMockComponent(XWikiContext.TYPE_PROVIDER, "readonly");
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }

    // Initialize stub context provider
    if (this.componentManager.hasComponent(XWikiStubContextProvider.class)) {
        XWikiStubContextProvider stubContextProvider = this.componentManager
                .getInstance(XWikiStubContextProvider.class);
        if (!MockUtil.isMock(stubContextProvider)) {
            stubContextProvider.initialize(this.context);
        }
    }

    // Make sure to have a mocked CoreConfiguration (even if one already exist)
    if (!this.componentManager.hasComponent(CoreConfiguration.class)) {
        CoreConfiguration coreConfigurationMock = this.componentManager
                .registerMockComponent(CoreConfiguration.class);
        when(coreConfigurationMock.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
    } else {
        CoreConfiguration coreConfiguration = this.componentManager
                .registerMockComponent(CoreConfiguration.class, false);
        if (MockUtil.isMock(coreConfiguration)) {
            when(coreConfiguration.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
        }
    }

    // Set a context ComponentManager if none exist
    if (!this.componentManager.hasComponent(ComponentManager.class, "context")) {
        DefaultComponentDescriptor<ComponentManager> componentManagerDescriptor = new DefaultComponentDescriptor<>();
        componentManagerDescriptor.setRoleHint("context");
        componentManagerDescriptor.setRoleType(ComponentManager.class);
        this.componentManager.registerComponent(componentManagerDescriptor, this.componentManager);
    }

    // XWiki

    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument doc = invocation.getArgument(0);
            String revision = invocation.getArgument(1);

            if (StringUtils.equals(revision, doc.getVersion())) {
                return doc;
            }

            // TODO: implement version store mocking
            return new XWikiDocument(doc.getDocumentReference());
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = invocation.getArgument(0);

            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }

            XWikiDocument document = documents.get(target);

            if (document == null) {
                document = new XWikiDocument(target, target.getLocale());
                document.setSyntax(Syntax.PLAIN_1_0);
                document.setOriginalDocument(document.clone());
            }

            return document;
        }
    }).when(getSpyXWiki()).getDocument(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument target = invocation.getArgument(0);

            return getSpyXWiki().getDocument(target.getDocumentReferenceWithLocale(),
                    invocation.getArgument(1));
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(XWikiContext.class));
    doAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = (DocumentReference) invocation.getArguments()[0];

            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }

            return documents.containsKey(target);
        }
    }).when(getSpyXWiki()).exists(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);
            String comment = invocation.getArgument(1);
            boolean minorEdit = invocation.getArgument(2);

            boolean isNew = document.isNew();

            document.setComment(StringUtils.defaultString(comment));
            document.setMinorEdit(minorEdit);

            if (document.isContentDirty() || document.isMetaDataDirty()) {
                document.setDate(new Date());
                if (document.isContentDirty()) {
                    document.setContentUpdateDate(new Date());
                    document.setContentAuthorReference(document.getAuthorReference());
                }
                document.incrementVersion();

                document.setContentDirty(false);
                document.setMetaDataDirty(false);
            }
            document.setNew(false);
            document.setStore(getMockStore());

            XWikiDocument previousDocument = documents.get(document.getDocumentReferenceWithLocale());

            if (previousDocument != null && previousDocument != document) {
                for (XWikiAttachment attachment : document.getAttachmentList()) {
                    if (!attachment.isContentDirty()) {
                        attachment.setAttachment_content(previousDocument
                                .getAttachment(attachment.getFilename()).getAttachment_content());
                    }
                }
            }

            XWikiDocument originalDocument = document.getOriginalDocument();
            if (originalDocument == null) {
                originalDocument = spyXWiki.getDocument(document.getDocumentReferenceWithLocale(), context);
                document.setOriginalDocument(originalDocument);
            }

            XWikiDocument savedDocument = document.clone();

            documents.put(document.getDocumentReferenceWithLocale(), savedDocument);

            if (isNew) {
                if (notifyDocumentCreatedEvent) {
                    getObservationManager().notify(new DocumentCreatedEvent(document.getDocumentReference()),
                            document, getXWikiContext());
                }
            } else {
                if (notifyDocumentUpdatedEvent) {
                    getObservationManager().notify(new DocumentUpdatedEvent(document.getDocumentReference()),
                            document, getXWikiContext());
                }
            }

            // Set the document as it's original document
            savedDocument.setOriginalDocument(savedDocument.clone());

            return null;
        }
    }).when(getSpyXWiki()).saveDocument(anyXWikiDocument(), any(String.class), anyBoolean(), anyXWikiContext());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);

            documents.remove(document.getDocumentReferenceWithLocale());

            if (notifyDocumentDeletedEvent) {
                getObservationManager().notify(new DocumentDeletedEvent(document.getDocumentReference()),
                        document, getXWikiContext());
            }

            return null;
        }
    }).when(getSpyXWiki()).deleteDocument(anyXWikiDocument(), any(Boolean.class), anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            return getSpyXWiki()
                    .getDocument((DocumentReference) invocation.getArguments()[0], invocation.getArgument(1))
                    .getXClass();
        }
    }).when(getSpyXWiki()).getXClass(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return getXWikiContext().getLanguage();
        }
    }).when(getSpyXWiki()).getLanguagePreference(anyXWikiContext());

    getXWikiContext().setLocale(Locale.ENGLISH);

    // XWikiStoreInterface

    when(getMockStore().getTranslationList(anyXWikiDocument(), anyXWikiContext()))
            .then(new Answer<List<String>>() {
                @Override
                public List<String> answer(InvocationOnMock invocation) throws Throwable {
                    XWikiDocument document = invocation.getArgument(0);

                    List<String> translations = new ArrayList<String>();

                    for (XWikiDocument storedDocument : documents.values()) {
                        Locale storedLocale = storedDocument.getLocale();
                        if (!storedLocale.equals(Locale.ROOT) && storedDocument.getDocumentReference()
                                .equals(document.getDocumentReference())) {
                            translations.add(storedLocale.toString());
                        }
                    }

                    return translations;
                }
            });
    when(getMockStore().loadXWikiDoc(anyXWikiDocument(), anyXWikiContext())).then(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0).getDocumentReference();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }

            return getSpyXWiki().getDocument(reference, xcontext);
        }
    });
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0)
                    .getDocumentReferenceWithLocale();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }

            documents.remove(reference);

            return null;
        }
    }).when(getMockStore()).deleteXWikiDoc(anyXWikiDocument(), anyXWikiContext());

    // Users

    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);

            XWikiDocument userDocument = getSpyXWiki().getDocument(
                    new DocumentReference(USER_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);

            final BaseClass userClass = userDocument.getXClass();

            if (userDocument.isNew()) {
                userClass.addTextField("first_name", "First Name", 30);
                userClass.addTextField("last_name", "Last Name", 30);
                userClass.addEmailField("email", "e-Mail", 30);
                userClass.addPasswordField("password", "Password", 10);
                userClass.addBooleanField("active", "Active", "active");
                userClass.addTextAreaField("comment", "Comment", 40, 5);
                userClass.addTextField("avatar", "Avatar", 30);
                userClass.addTextField("phone", "Phone", 30);
                userClass.addTextAreaField("address", "Address", 40, 3);

                getSpyXWiki().saveDocument(userDocument, xcontext);
            }

            return userClass;
        }
    }).when(getSpyXWiki()).getUserClass(anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);

            XWikiDocument groupDocument = getSpyXWiki().getDocument(
                    new DocumentReference(GROUP_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);

            final BaseClass groupClass = groupDocument.getXClass();

            if (groupDocument.isNew()) {
                groupClass.addTextField("member", "Member", 30);

                getSpyXWiki().saveDocument(groupDocument, xcontext);
            }

            return groupClass;
        }
    }).when(getSpyXWiki()).getGroupClass(anyXWikiContext());

    // Query Manager
    // If there's already a Query Manager registered, use it instead.
    // This allows, for example, using @ComponentList to use the real Query Manager, in integration tests.
    if (!this.componentManager.hasComponent(QueryManager.class)) {
        mockQueryManager();
    }
    when(getMockStore().getQueryManager()).then(new Answer<QueryManager>() {

        @Override
        public QueryManager answer(InvocationOnMock invocation) throws Throwable {
            return getQueryManager();
        }
    });

    // WikiDescriptorManager
    // If there's already a WikiDescriptorManager registered, use it instead.
    // This allows, for example, using @ComponentList to use the real WikiDescriptorManager, in integration tests.
    if (!this.componentManager.hasComponent(WikiDescriptorManager.class)) {
        this.wikiDescriptorManager = getMocker().registerMockComponent(WikiDescriptorManager.class);
        when(this.wikiDescriptorManager.getMainWikiId()).then(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getMainXWiki();
            }
        });
        when(this.wikiDescriptorManager.getCurrentWikiId()).then(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getWikiId();
            }
        });
    }
}

From source file:com.xpn.xwiki.test.MockitoOldcoreRule.java

protected void before(Class<?> testClass) throws Exception {
    // Statically store the component manager in {@link Utils} to be able to access it without
    // the context.
    Utils.setComponentManager(getMocker());

    this.context = new XWikiContext();

    getXWikiContext().setWikiId("xwiki");
    getXWikiContext().setMainXWiki("xwiki");

    this.spyXWiki = spy(new XWiki());
    getXWikiContext().setWiki(this.spyXWiki);

    this.mockHibernateStore = mock(XWikiHibernateStore.class);
    this.mockVersioningStore = mock(XWikiVersioningStoreInterface.class);
    this.mockRightService = mock(XWikiRightService.class);
    this.mockGroupService = mock(XWikiGroupService.class);

    doReturn(this.mockHibernateStore).when(this.spyXWiki).getStore();
    doReturn(this.mockHibernateStore).when(this.spyXWiki).getHibernateStore();
    doReturn(this.mockVersioningStore).when(this.spyXWiki).getVersioningStore();
    doReturn(this.mockRightService).when(this.spyXWiki).getRightService();
    doReturn(this.mockGroupService).when(this.spyXWiki).getGroupService(getXWikiContext());

    // We need to initialize the Component Manager so that the components can be looked up
    getXWikiContext().put(ComponentManager.class.getName(), getMocker());

    if (testClass.getAnnotation(AllComponents.class) != null) {
        // If @AllComponents is enabled force mocking AuthorizationManager and ContextualAuthorizationManager if not
        // already mocked
        this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class, false);
        this.mockContextualAuthorizationManager = getMocker()
                .registerMockComponent(ContextualAuthorizationManager.class, false);
    } else {//from   w w  w .  java  2s  .c o m
        // Make sure an AuthorizationManager and a ContextualAuthorizationManager is available
        if (!getMocker().hasComponent(AuthorizationManager.class)) {
            this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class);
        }
        if (!getMocker().hasComponent(ContextualAuthorizationManager.class)) {
            this.mockContextualAuthorizationManager = getMocker()
                    .registerMockComponent(ContextualAuthorizationManager.class);
        }
    }

    // Make sure a default ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class)) {
        this.configurationSource = getMocker().registerMemoryConfigurationSource();
    }

    // Make sure a "xwikicfg" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT)) {
        this.xwikicfgConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(
                MockConfigurationSource.getDescriptor(XWikiCfgConfigurationSource.ROLEHINT),
                this.xwikicfgConfigurationSource);
    }
    // Make sure a "wiki" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "wiki")) {
        this.wikiConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("wiki"),
                this.wikiConfigurationSource);
    }

    // Make sure a "space" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "space")) {
        this.spaceConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("space"),
                this.spaceConfigurationSource);
    }

    // Since the oldcore module draws the Servlet Environment in its dependencies we need to ensure it's set up
    // correctly with a Servlet Context.
    if (getMocker().hasComponent(Environment.class)
            && getMocker().getInstance(Environment.class) instanceof ServletEnvironment) {
        ServletEnvironment environment = getMocker().getInstance(Environment.class);

        ServletContext servletContextMock = mock(ServletContext.class);
        environment.setServletContext(servletContextMock);
        when(servletContextMock.getAttribute("javax.servlet.context.tempdir"))
                .thenReturn(new File(System.getProperty("java.io.tmpdir")));

        File testDirectory = new File("target/test-" + new Date().getTime());
        this.temporaryDirectory = new File(testDirectory, "temporary-dir");
        this.permanentDirectory = new File(testDirectory, "permanent-dir");
        environment.setTemporaryDirectory(this.temporaryDirectory);
        environment.setPermanentDirectory(this.permanentDirectory);
    }

    // Initialize the Execution Context
    if (this.componentManager.hasComponent(ExecutionContextManager.class)) {
        ExecutionContextManager ecm = this.componentManager.getInstance(ExecutionContextManager.class);
        ExecutionContext ec = new ExecutionContext();
        ecm.initialize(ec);
    }

    // Bridge with old XWiki Context, required for old code.
    Execution execution;
    if (this.componentManager.hasComponent(Execution.class)) {
        execution = this.componentManager.getInstance(Execution.class);
    } else {
        execution = this.componentManager.registerMockComponent(Execution.class);
    }
    ExecutionContext econtext;
    if (MockUtil.isMock(execution)) {
        econtext = new ExecutionContext();
        when(execution.getContext()).thenReturn(econtext);
    } else {
        econtext = execution.getContext();
    }

    // Set a few standard things in the ExecutionContext
    econtext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, this.context);
    this.scriptContext = (ScriptContext) econtext
            .getProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID);
    if (this.scriptContext == null) {
        this.scriptContext = new SimpleScriptContext();
        econtext.setProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID, this.scriptContext);
    }

    if (!this.componentManager.hasComponent(ScriptContextManager.class)) {
        ScriptContextManager scriptContextManager = this.componentManager
                .registerMockComponent(ScriptContextManager.class);
        when(scriptContextManager.getCurrentScriptContext()).thenReturn(this.scriptContext);
        when(scriptContextManager.getScriptContext()).thenReturn(this.scriptContext);
    }

    // Initialize XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER)) {
        Provider<XWikiContext> xcontextProvider = this.componentManager
                .registerMockComponent(XWikiContext.TYPE_PROVIDER);
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }

    // Initialize readonly XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER, "readonly")) {
        Provider<XWikiContext> xcontextProvider = this.componentManager
                .registerMockComponent(XWikiContext.TYPE_PROVIDER, "readonly");
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }

    // Initialize stub context provider
    if (this.componentManager.hasComponent(XWikiStubContextProvider.class)) {
        XWikiStubContextProvider stubContextProvider = this.componentManager
                .getInstance(XWikiStubContextProvider.class);
        if (!MockUtil.isMock(stubContextProvider)) {
            stubContextProvider.initialize(this.context);
        }
    }

    // Make sure to have a mocked CoreConfiguration (even if one already exist)
    if (!this.componentManager.hasComponent(CoreConfiguration.class)) {
        CoreConfiguration coreConfigurationMock = this.componentManager
                .registerMockComponent(CoreConfiguration.class);
        when(coreConfigurationMock.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
    } else {
        CoreConfiguration coreConfiguration = this.componentManager
                .registerMockComponent(CoreConfiguration.class, false);
        if (MockUtil.isMock(coreConfiguration)) {
            when(coreConfiguration.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
        }
    }

    // Set a context ComponentManager if none exist
    if (!this.componentManager.hasComponent(ComponentManager.class, "context")) {
        DefaultComponentDescriptor<ComponentManager> componentManagerDescriptor = new DefaultComponentDescriptor<>();
        componentManagerDescriptor.setRoleHint("context");
        componentManagerDescriptor.setRoleType(ComponentManager.class);
        this.componentManager.registerComponent(componentManagerDescriptor, this.componentManager);
    }

    // XWiki

    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument doc = invocation.getArgument(0);
            String revision = invocation.getArgument(1);

            if (StringUtils.equals(revision, doc.getVersion())) {
                return doc;
            }

            // TODO: implement version store mocking
            return new XWikiDocument(doc.getDocumentReference());
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = invocation.getArgument(0);

            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }

            XWikiDocument document = documents.get(target);

            if (document == null) {
                document = new XWikiDocument(target, target.getLocale());
                document.setSyntax(Syntax.PLAIN_1_0);
                document.setOriginalDocument(document.clone());
            }

            return document;
        }
    }).when(getSpyXWiki()).getDocument(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument target = invocation.getArgument(0);

            return getSpyXWiki().getDocument(target.getDocumentReferenceWithLocale(),
                    invocation.getArgument(1));
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(XWikiContext.class));
    doAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = (DocumentReference) invocation.getArguments()[0];

            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }

            return documents.containsKey(target);
        }
    }).when(getSpyXWiki()).exists(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);
            String comment = invocation.getArgument(1);
            boolean minorEdit = invocation.getArgument(2);

            boolean isNew = document.isNew();

            document.setComment(StringUtils.defaultString(comment));
            document.setMinorEdit(minorEdit);

            if (document.isContentDirty() || document.isMetaDataDirty()) {
                document.setDate(new Date());
                if (document.isContentDirty()) {
                    document.setContentUpdateDate(new Date());
                    document.setContentAuthorReference(document.getAuthorReference());
                }
                document.incrementVersion();

                document.setContentDirty(false);
                document.setMetaDataDirty(false);
            }
            document.setNew(false);
            document.setStore(getMockStore());

            XWikiDocument previousDocument = documents.get(document.getDocumentReferenceWithLocale());

            if (previousDocument != null && previousDocument != document) {
                for (XWikiAttachment attachment : document.getAttachmentList()) {
                    if (!attachment.isContentDirty()) {
                        attachment.setAttachment_content(previousDocument
                                .getAttachment(attachment.getFilename()).getAttachment_content());
                    }
                }
            }

            XWikiDocument originalDocument = document.getOriginalDocument();
            if (originalDocument == null) {
                originalDocument = spyXWiki.getDocument(document.getDocumentReferenceWithLocale(), context);
                document.setOriginalDocument(originalDocument);
            }

            XWikiDocument savedDocument = document.clone();

            documents.put(document.getDocumentReferenceWithLocale(), savedDocument);

            if (isNew) {
                if (notifyDocumentCreatedEvent) {
                    getObservationManager().notify(new DocumentCreatedEvent(document.getDocumentReference()),
                            document, getXWikiContext());
                }
            } else {
                if (notifyDocumentUpdatedEvent) {
                    getObservationManager().notify(new DocumentUpdatedEvent(document.getDocumentReference()),
                            document, getXWikiContext());
                }
            }

            // Set the document as it's original document
            savedDocument.setOriginalDocument(savedDocument.clone());

            return null;
        }
    }).when(getSpyXWiki()).saveDocument(anyXWikiDocument(), any(String.class), anyBoolean(), anyXWikiContext());
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);

            documents.remove(document.getDocumentReferenceWithLocale());

            if (notifyDocumentDeletedEvent) {
                getObservationManager().notify(new DocumentDeletedEvent(document.getDocumentReference()),
                        document, getXWikiContext());
            }

            return null;
        }
    }).when(getSpyXWiki()).deleteDocument(anyXWikiDocument(), any(Boolean.class), anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            return getSpyXWiki()
                    .getDocument((DocumentReference) invocation.getArguments()[0], invocation.getArgument(1))
                    .getXClass();
        }
    }).when(getSpyXWiki()).getXClass(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return getXWikiContext().getLanguage();
        }
    }).when(getSpyXWiki()).getLanguagePreference(anyXWikiContext());

    getXWikiContext().setLocale(Locale.ENGLISH);

    // XWikiStoreInterface

    when(getMockStore().getTranslationList(anyXWikiDocument(), anyXWikiContext()))
            .then(new Answer<List<String>>() {
                @Override
                public List<String> answer(InvocationOnMock invocation) throws Throwable {
                    XWikiDocument document = invocation.getArgument(0);

                    List<String> translations = new ArrayList<String>();

                    for (XWikiDocument storedDocument : documents.values()) {
                        Locale storedLocale = storedDocument.getLocale();
                        if (!storedLocale.equals(Locale.ROOT) && storedDocument.getDocumentReference()
                                .equals(document.getDocumentReference())) {
                            translations.add(storedLocale.toString());
                        }
                    }

                    return translations;
                }
            });
    when(getMockStore().loadXWikiDoc(anyXWikiDocument(), anyXWikiContext())).then(new Answer<XWikiDocument>() {
        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0).getDocumentReference();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }

            return getSpyXWiki().getDocument(reference, xcontext);
        }
    });
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0)
                    .getDocumentReferenceWithLocale();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }

            documents.remove(reference);

            return null;
        }
    }).when(getMockStore()).deleteXWikiDoc(anyXWikiDocument(), anyXWikiContext());

    // Users

    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);

            XWikiDocument userDocument = getSpyXWiki().getDocument(
                    new DocumentReference(USER_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);

            final BaseClass userClass = userDocument.getXClass();

            if (userDocument.isNew()) {
                userClass.addTextField("first_name", "First Name", 30);
                userClass.addTextField("last_name", "Last Name", 30);
                userClass.addEmailField("email", "e-Mail", 30);
                userClass.addPasswordField("password", "Password", 10);
                userClass.addBooleanField("active", "Active", "active");
                userClass.addTextAreaField("comment", "Comment", 40, 5);
                userClass.addTextField("avatar", "Avatar", 30);
                userClass.addTextField("phone", "Phone", 30);
                userClass.addTextAreaField("address", "Address", 40, 3);

                getSpyXWiki().saveDocument(userDocument, xcontext);
            }

            return userClass;
        }
    }).when(getSpyXWiki()).getUserClass(anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {
        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);

            XWikiDocument groupDocument = getSpyXWiki().getDocument(
                    new DocumentReference(GROUP_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);

            final BaseClass groupClass = groupDocument.getXClass();

            if (groupDocument.isNew()) {
                groupClass.addTextField("member", "Member", 30);

                getSpyXWiki().saveDocument(groupDocument, xcontext);
            }

            return groupClass;
        }
    }).when(getSpyXWiki()).getGroupClass(anyXWikiContext());

    // Query Manager
    // If there's already a Query Manager registered, use it instead.
    // This allows, for example, using @ComponentList to use the real Query Manager, in integration tests.
    if (!this.componentManager.hasComponent(QueryManager.class)) {
        mockQueryManager();
    }
    when(getMockStore().getQueryManager()).then(new Answer<QueryManager>() {

        @Override
        public QueryManager answer(InvocationOnMock invocation) throws Throwable {
            return getQueryManager();
        }
    });

    // WikiDescriptorManager
    // If there's already a WikiDescriptorManager registered, use it instead.
    // This allows, for example, using @ComponentList to use the real WikiDescriptorManager, in integration tests.
    if (!this.componentManager.hasComponent(WikiDescriptorManager.class)) {
        this.wikiDescriptorManager = getMocker().registerMockComponent(WikiDescriptorManager.class);
        when(this.wikiDescriptorManager.getMainWikiId()).then(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getMainXWiki();
            }
        });
        when(this.wikiDescriptorManager.getCurrentWikiId()).then(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getWikiId();
            }
        });
    }
}

From source file:org.itracker.services.implementations.ConfigurationServiceImpl.java

@Override
public Language getLanguageItemByKey(String key, Locale locale) {
    String localeString = ITrackerResources.BASE_LOCALE;
    if (null != locale && !locale.equals(ITrackerResources.getLocale(ITrackerResources.BASE_LOCALE))) {
        localeString = locale.toString();
    }/* w w w .  ja v  a 2 s  . c  om*/
    Language languageItem = languageDAO.findByKeyAndLocale(key, localeString);
    // TODO: obsolete code:
    //        try {
    //            languageItem = languageDAO.findByKeyAndLocale(key, ITrackerResources.BASE_LOCALE);
    //        } catch (RuntimeException e) {
    //            logger.debug("could not find {}with BASE", key);
    //            languageItem = null;
    //        }
    //
    //        if (null == locale) {
    //            logger.debug("locale was null, returning BASE: {}", languageItem);
    //            return languageItem;
    //        }
    //        try {
    //            languageItem = languageDAO.findByKeyAndLocale(key, locale.getLanguage());
    //        } catch (RuntimeException re) {
    //            logger.debug("could not find {}with language {}", key, locale.getLanguage());
    //        }
    //        if (StringUtils.isNotEmpty(locale.getCountry())) {
    //            try {
    //                languageItem = languageDAO.findByKeyAndLocale(key, locale.toString());
    //            } catch (RuntimeException ex) {
    //                logger.debug("could not find {}with locale {}", key, locale);
    //            }
    //        }

    return languageItem;

}

From source file:com.appeaser.sublimepickerlibrary.timepicker.SublimeTimePicker.java

public void setCurrentLocale(Locale locale) {
    if (locale.equals(mCurrentLocale)) {
        return;/*from  w  w  w. j a  v a  2 s. c o  m*/
    }
    mCurrentLocale = locale;

    mTempCalendar = Calendar.getInstance(locale);
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDateParser.java

/**
 * <p>Constructs a new FastDateParser.</p>
 *
 * @param pattern non-null {@link java.text.SimpleDateFormat} compatible
 *  pattern/*from w ww.j a v a2s .c  om*/
 * @param timeZone non-null time zone to use
 * @param locale non-null locale
 * @param centuryStart The start of the century for 2 digit year parsing
 *
 * @since 3.5
 */
protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale,
        final Date centuryStart) {
    this.pattern = pattern;
    this.timeZone = timeZone;
    this.locale = locale;

    final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);

    int centuryStartYear;
    if (centuryStart != null) {
        definingCalendar.setTime(centuryStart);
        centuryStartYear = definingCalendar.get(Calendar.YEAR);
    } else if (locale.equals(JAPANESE_IMPERIAL)) {
        centuryStartYear = 0;
    } else {
        // from 80 years ago to 20 years from now
        definingCalendar.setTime(new Date());
        centuryStartYear = definingCalendar.get(Calendar.YEAR) - 80;
    }
    century = centuryStartYear / 100 * 100;
    startYear = centuryStartYear - century;

    init(definingCalendar);
}