Example usage for java.util Locale toString

List of usage examples for java.util Locale toString

Introduction

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

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions as below:
language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensions
Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.

Usage

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractBillingController.java

@RequestMapping(value = { "/generatePdfInvoice" }, method = RequestMethod.GET)
public String generatePdfAccountStatement(@ModelAttribute("currentTenant") Tenant tenant,
        @RequestParam(value = "viewBy", required = false) String viewBy,
        @RequestParam(value = "tenant", required = false) String tenantParam,
        @RequestParam(value = "accountStatementUuid", required = false) String accountStatementUuid,
        @RequestParam(value = "page", required = false, defaultValue = "1") String currentPage, ModelMap map,
        HttpServletRequest request, HttpServletResponse response) {

    logger.debug("###Entering in generatePdfAccountStaement method @GET");

    Tenant effectiveTenant = (Tenant) request.getAttribute(UserContextInterceptor.EFFECTIVE_TENANT_KEY);

    String targetXmlFile = "UB" + System.currentTimeMillis() + "." + "pdf";

    OutputStream pdfOut = null;/* w w w . j  av a  2 s  .c  o  m*/
    AccountStatement accountStatement = billingService.getAccountStatement(accountStatementUuid);
    Locale locale = getCurrentUser().getLocale() != null ? getCurrentUser().getLocale() : getDefaultLocale();
    String pdfHtmlString = getInvoicePdfHtmlString(effectiveTenant, accountStatement, locale.toString());

    if (pdfHtmlString != null) {
        ByteArrayInputStream htmlSource;
        try {
            htmlSource = new ByteArrayInputStream(pdfHtmlString.getBytes("UTF-8"));
            pdfOut = pdfGenerator.generatePdfFromHtml(htmlSource);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    if (pdfOut != null) {
        response.setHeader("Content-Disposition", "attachment; filename=" + targetXmlFile);
        response.setContentType("application/pdf");
        OutputStream out = null;
        InputStream is = null;
        try {
            out = response.getOutputStream();
            is = new BufferedInputStream(
                    new ByteArrayInputStream(((ByteArrayOutputStream) pdfOut).toByteArray()));
            FileCopyUtils.copy(is, response.getOutputStream());
            out.flush();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                out.close();
            } catch (IOException e) {
                logger.error("Error while closing streams", e);
            }
        }
    } else {
        return "generatePdfAccountStatement.error";
    }
    return null;
}

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 ww  w.j a  v a  2  s  .  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: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 {//  w  w  w .j  av  a 2 s .c om
        // 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.alfresco.repo.web.scripts.bean.KeywordSearch.java

/**
 * Execute the search/*from ww w  .  ja  v  a 2s.c o m*/
 */
private SearchResult search(String searchTerms, int startPage, int itemsPerPage, Locale locale,
        WebScriptRequest req) {
    SearchResult searchResult = null;
    ResultSet results = null;

    try {
        // construct search statement
        String[] terms = searchTerms.split(" ");
        searchTerms = searchTerms.replaceAll("\"", "&quot;");

        // Escape special characters in the terms, so that they can't confuse the parser 
        for (int i = 0; i < terms.length; i++) {
            terms[i] = SearchLanguageConversion.escapeLuceneQuery(terms[i]);
        }

        Map<String, Object> statementModel = new HashMap<String, Object>(7, 1.0f);
        statementModel.put("args", createArgs(req));
        statementModel.put("terms", terms);
        Writer queryWriter = new StringWriter(1024);
        renderFormatTemplate(QUERY_FORMAT, statementModel, queryWriter);
        String query = queryWriter.toString();

        // execute query
        if (logger.isDebugEnabled()) {
            logger.debug("Search parameters: searchTerms=" + searchTerms + ", startPage=" + startPage
                    + ", itemsPerPage=" + itemsPerPage + ", search locale=" + locale.toString());
            logger.debug("Issuing lucene search: " + query);
        }

        SearchParameters parameters = new SearchParameters();
        parameters.addStore(SEARCH_STORE);
        parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
        parameters.setQuery(query);
        if (locale != null) {
            parameters.addLocale(locale);
        }
        results = searchService.query(parameters);
        int totalResults = results.length();

        if (logger.isDebugEnabled())
            logger.debug("Results: " + totalResults + " rows (limited: "
                    + results.getResultSetMetaData().getLimitedBy() + ")");

        // are we out-of-range
        int totalPages = (totalResults / itemsPerPage);
        totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0;
        if (totalPages != 0 && (startPage < 1 || startPage > totalPages)) {
            throw new WebScriptException(
                    "Start page " + startPage + " is outside boundary of " + totalPages + " pages");
        }

        // construct search result
        searchResult = new SearchResult();
        searchResult.setSearchTerms(searchTerms);
        searchResult.setLocale(locale);
        searchResult.setItemsPerPage(itemsPerPage);
        searchResult.setStartPage(startPage);
        searchResult.setTotalResults(totalResults);
        if (totalResults == 0) {
            searchResult.setTotalPages(0);
            searchResult.setStartIndex(0);
            searchResult.setTotalPageItems(0);
        } else {
            searchResult.setTotalPages(totalPages);
            searchResult.setStartIndex(((startPage - 1) * itemsPerPage) + 1);
            searchResult
                    .setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1));
        }
        SearchTemplateNode[] nodes = new SearchTemplateNode[searchResult.getTotalPageItems()];
        for (int i = 0; i < searchResult.getTotalPageItems(); i++) {
            NodeRef node = results.getNodeRef(i + searchResult.getStartIndex() - 1);
            // Make the search resilient to invalid nodes
            if (!nodeService.exists(node)) {
                continue;
            }
            float score = results.getScore(i + searchResult.getStartIndex() - 1);
            nodes[i] = new SearchTemplateNode(node, score);
        }
        searchResult.setResults(nodes);
        return searchResult;
    } finally {
        if (results != null) {
            results.close();
        }
    }
}

From source file:com.octo.captcha.engine.bufferedengine.buffer.DatabaseCaptchaBuffer.java

/**
 * Put a collection of captchas with his locale
 *
 * @param captchas The captchas to add/*from  w  ww  .jav a2  s . co m*/
 * @param locale   The locale of the captchas
 */
public void putAllCaptcha(Collection captchas, Locale locale) {
    Connection con = null;
    PreparedStatement ps = null;

    if (captchas != null && captchas.size() > 0) {
        Iterator captIt = captchas.iterator();
        if (log.isDebugEnabled()) {
            log.debug("try to insert " + captchas.size() + " captchas");
        }

        try {
            con = datasource.getConnection();
            con.setAutoCommit(false);
            ps = con.prepareStatement("insert into " + table + "(" + timeMillisColumn + "," + hashCodeColumn
                    + "," + localeColumn + "," + captchaColumn + ") values (?,?,?,?)");

            while (captIt.hasNext()) {

                Captcha captcha = (Captcha) captIt.next();
                try {
                    long currenttime = System.currentTimeMillis();
                    long hash = captcha.hashCode();

                    ps.setLong(1, currenttime);
                    ps.setLong(2, hash);
                    ps.setString(3, locale.toString());
                    // Serialise the entry
                    final ByteArrayOutputStream outstr = new ByteArrayOutputStream();
                    final ObjectOutputStream objstr = new ObjectOutputStream(outstr);
                    objstr.writeObject(captcha);
                    objstr.close();
                    final ByteArrayInputStream inpstream = new ByteArrayInputStream(outstr.toByteArray());

                    ps.setBinaryStream(4, inpstream, outstr.size());

                    ps.addBatch();

                    if (log.isDebugEnabled()) {
                        log.debug("insert captcha added to batch : " + currenttime + ";" + hash);
                    }

                } catch (IOException e) {
                    log.warn("error during captcha serialization, "
                            + "check your class versions. removing row from database", e);
                }
            }
            //exexute batch and commit()

            ps.executeBatch();
            log.debug("batch executed");

            con.commit();
            log.debug("batch commited");

        } catch (SQLException e) {
            log.error(DB_ERROR, e);

        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                }
            }
        }
    }

}

From source file:org.atomserver.core.AbstractAtomCollection.java

protected Entry newEntry(Abdera abdera, EntryMetaData entryMetaData, EntryType entryType)
        throws AtomServerException {

    StopWatch outerStopWatch = new AtomServerStopWatch();
    try {/*w  ww. j a va 2  s.c  o m*/
        Entry entry = newEntryWithCommonContentOnly(abdera, entryMetaData);

        java.util.Date updated = entryMetaData.getUpdatedDate();
        java.util.Date published = entryMetaData.getPublishedDate();

        entry.setUpdated(updated);
        if (published != null) {
            entry.setPublished(published);
        }

        String workspace = entryMetaData.getWorkspace();
        String collection = entryMetaData.getCollection();
        String entryId = entryMetaData.getEntryId();
        java.util.Locale locale = entryMetaData.getLocale();

        if (locale != null) {
            entry.addSimpleExtension(AtomServerConstants.LOCALE, locale.toString());
        }

        String fileURI = getURIHandler().constructURIString(workspace, collection, entryId, locale);

        addCategoriesToEntry(entry, entryMetaData, abdera);

        StopWatch contentStopWatch = new AtomServerStopWatch();
        try {
            if (entryType == EntryType.full) {
                addFullEntryContent(abdera, entryMetaData, entry);
            } else if (entryType == EntryType.link) {
                addLinkToEntry(AtomServer.getFactory(abdera), entry, fileURI, "alternate");
            } else {
                throw new AtomServerException("Must define the EntryType -- full or link");
            }
        } finally {
            contentStopWatch.stop("XML.entry.addContent",
                    AtomServerPerfLogTagFormatter.getPerfLogEntryString(entryMetaData));
        }

        return entry;

    } catch (Exception ee) {
        String msg = "Exception " + ee.getClass().getSimpleName() + " while creating XML for: " + entryMetaData;
        log.error(ee);
        throw (ee instanceof AtomServerException) ? (AtomServerException) ee : new AtomServerException(msg, ee);

    } finally {
        outerStopWatch.stop("XML.entry.all",
                AtomServerPerfLogTagFormatter.getPerfLogEntryString(entryMetaData));
    }
}

From source file:org.jahia.ajax.gwt.helper.ContentDefinitionHelper.java

/**
 * Get both dynamic and static default values for the specified types and locales
 *
 * @param items   a list of nodeTypes//from  w w w . j  a  v a  2  s. co  m
 * @param locales a list of locales
 * @return the default values per type, per locale
 * @throws RepositoryException
 */
public Map<String, Map<String, List<GWTJahiaNodePropertyValue>>> getAllDefaultValues(
        List<ExtendedNodeType> items, List<Locale> locales) throws RepositoryException {
    Set<Map.Entry<String, ExtendedPropertyDefinition>> entries = getInitializedItems(items).entrySet();
    Map<String, Map<String, List<GWTJahiaNodePropertyValue>>> results = new HashMap<String, Map<String, List<GWTJahiaNodePropertyValue>>>();
    for (Locale locale : locales) {
        Map<String, List<GWTJahiaNodePropertyValue>> defaultValues = new HashMap<String, List<GWTJahiaNodePropertyValue>>();
        for (Map.Entry<String, ExtendedPropertyDefinition> entry : entries) {
            List<GWTJahiaNodePropertyValue> propertyDefaultValues = new ArrayList<GWTJahiaNodePropertyValue>();
            for (Value value : entry.getValue().getDefaultValues(locale)) {
                propertyDefaultValues.add(convertValue(value, entry.getValue()));
            }
            defaultValues.put(entry.getKey(), propertyDefaultValues);
        }
        results.put(locale.toString(), defaultValues);
    }
    return results;
}

From source file:org.jahia.services.sites.JahiaSitesBaseService.java

public void initAfterAllServicesAreStarted() throws JahiaInitializationException {
    try {//from  w w w  .  ja  v a2s  .c  o  m
        JahiaUser jahiaUser = JCRSessionFactory.getInstance().getCurrentUser();
        if (getNbSites() == 0) {
            Locale selectedLocale = LanguageCodeConverters.languageCodeToLocale(systemSiteDefaultLanguage);
            JahiaSite site = addSite(jahiaUser, systemSiteTitle, systemSiteServername, SYSTEM_SITE_KEY, "",
                    selectedLocale, systemSiteTemplateSetName, null, "noImport", null, null, false, false,
                    null);
            site.setMixLanguagesActive(true);
            site.setLanguages(systemSiteLanguages);
            updateSite(site);
            final LinkedHashSet<String> languages = new LinkedHashSet<String>();
            languages.add(selectedLocale.toString());
            final List<String> uuids = new ArrayList<String>();
            try {
                JCRNodeWrapper node = (JCRNodeWrapper) sessionFactory.getCurrentUserSession()
                        .getNode(SITES_JCR_PATH).getNodes().nextNode();
                node.checkout();
                //                     node.changeRoles("g:users","re---");
                uuids.add(node.getIdentifier());
                List<PublicationInfo> publicationInfos = JCRPublicationService.getInstance().getPublicationInfo(
                        node.getIdentifier(), languages, true, true, true, Constants.EDIT_WORKSPACE,
                        Constants.LIVE_WORKSPACE);
                for (PublicationInfo publicationInfo : publicationInfos) {
                    if (publicationInfo.needPublication(null)) {
                        uuids.addAll(publicationInfo.getAllUuids());
                    }
                }
                JCRPublicationService.getInstance().publish(uuids, Constants.EDIT_WORKSPACE,
                        Constants.LIVE_WORKSPACE, null);
            } catch (RepositoryException e) {
                logger.error(e.getMessage(), e);
            } finally {
                JCRSessionFactory.getInstance().closeAllSessions();
            }
        }
    } catch (JahiaException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.codelibs.fess.web.IndexAction.java

protected String doSearchInternal() {
    final StringBuilder queryBuf = new StringBuilder(255);
    if (StringUtil.isNotBlank(indexForm.query)) {
        queryBuf.append(indexForm.query);
    }//from w  ww .ja  va 2 s.  com
    if (StringUtil.isNotBlank(indexForm.op)) {
        request.setAttribute(Constants.DEFAULT_OPERATOR, indexForm.op);
    }
    if (queryBuf.indexOf(" OR ") >= 0) {
        queryBuf.insert(0, '(').append(')');
    }
    if (indexForm.additional != null) {
        final Set<String> fieldSet = new HashSet<String>();
        for (final String additional : indexForm.additional) {
            if (StringUtil.isNotBlank(additional) && additional.length() < 1000
                    && !hasFieldInQuery(fieldSet, additional)) {
                queryBuf.append(' ').append(additional);
            }
        }
    }
    if (!indexForm.fields.isEmpty()) {
        for (final Map.Entry<String, String[]> entry : indexForm.fields.entrySet()) {
            final List<String> valueList = new ArrayList<String>();
            final String[] values = entry.getValue();
            if (values != null) {
                for (final String v : values) {
                    valueList.add(v);
                }
            }
            if (valueList.size() == 1) {
                queryBuf.append(' ').append(entry.getKey()).append(":\"").append(valueList.get(0)).append('\"');
            } else if (valueList.size() > 1) {
                queryBuf.append(" (");
                for (int i = 0; i < valueList.size(); i++) {
                    if (i != 0) {
                        queryBuf.append(" OR");
                    }
                    queryBuf.append(' ').append(entry.getKey()).append(":\"").append(valueList.get(i))
                            .append('\"');
                }
                queryBuf.append(')');
            }

        }
    }
    if (StringUtil.isNotBlank(indexForm.sort)) {
        queryBuf.append(" sort:").append(indexForm.sort);
    }
    if (indexForm.lang != null) {
        final Set<String> langSet = new HashSet<>();
        for (final String lang : indexForm.lang) {
            if (StringUtil.isNotBlank(lang) && lang.length() < 1000) {
                if (Constants.ALL_LANGUAGES.equalsIgnoreCase(lang)) {
                    langSet.add(Constants.ALL_LANGUAGES);
                } else {
                    final String normalizeLang = systemHelper.normalizeLang(lang);
                    if (normalizeLang != null) {
                        langSet.add(normalizeLang);
                    }
                }
            }
        }
        if (langSet.size() > 1 && langSet.contains(Constants.ALL_LANGUAGES)) {
            langSet.clear();
            indexForm.lang = new String[] { Constants.ALL_LANGUAGES };
        } else {
            langSet.remove(Constants.ALL_LANGUAGES);
        }
        appendLangQuery(queryBuf, langSet);
    } else if (Constants.TRUE.equals(
            crawlerProperties.getProperty(Constants.USE_BROWSER_LOCALE_FOR_SEARCH_PROPERTY, Constants.FALSE))) {
        final Set<String> langSet = new HashSet<>();
        final Enumeration<Locale> locales = request.getLocales();
        if (locales != null) {
            while (locales.hasMoreElements()) {
                final Locale locale = locales.nextElement();
                final String normalizeLang = systemHelper.normalizeLang(locale.toString());
                if (normalizeLang != null) {
                    langSet.add(normalizeLang);
                }
            }
            if (!langSet.isEmpty()) {
                appendLangQuery(queryBuf, langSet);
            }
        }
    }

    final String query = queryBuf.toString().trim();

    // init pager
    if (StringUtil.isBlank(indexForm.start)) {
        indexForm.start = String.valueOf(DEFAULT_START_COUNT);
    } else {
        try {
            Long.parseLong(indexForm.start);
        } catch (final NumberFormatException e) {
            indexForm.start = String.valueOf(DEFAULT_START_COUNT);
        }
    }
    if (StringUtil.isBlank(indexForm.num)) {
        indexForm.num = String.valueOf(getDefaultPageSize());
    }
    normalizePageNum();

    final int pageStart = Integer.parseInt(indexForm.start);
    final int pageNum = Integer.parseInt(indexForm.num);
    try {
        documentItems = searchService.getDocumentList(query, pageStart, pageNum, indexForm.facet, indexForm.geo,
                indexForm.mlt, queryHelper.getResponseFields(), queryHelper.getResponseDocValuesFields());
    } catch (final SolrLibQueryException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, "errors.invalid_query_unknown");
    } catch (final InvalidQueryException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, e.getMessageCode());
    } catch (final ResultOffsetExceededException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, "errors.result_size_exceeded");
    }
    // search
    final QueryResponseList queryResponseList = (QueryResponseList) documentItems;
    facetResponse = queryResponseList.getFacetResponse();
    moreLikeThisResponse = queryResponseList.getMoreLikeThisResponse();
    final NumberFormat nf = NumberFormat.getInstance(RequestUtil.getRequest().getLocale());
    nf.setMaximumIntegerDigits(2);
    nf.setMaximumFractionDigits(2);
    try {
        execTime = nf.format((double) queryResponseList.getExecTime() / 1000);
    } catch (final Exception e) {
        // ignore
    }

    final Clock clock = Clock.systemDefaultZone();
    indexForm.rt = Long.toString(clock.millis());

    // favorite
    if (favoriteSupport || screenShotManager != null) {
        indexForm.queryId = userInfoHelper.generateQueryId(query, documentItems);
        if (screenShotManager != null) {
            screenShotManager.storeRequest(indexForm.queryId, documentItems);
            screenShotSupport = true;
        }
    }

    // search log
    if (searchLogSupport) {
        final LocalDateTime now = systemHelper.getCurrentTime();

        final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
        final SearchLog searchLog = new SearchLog();

        String userCode = null;
        if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.USER_INFO_PROPERTY, Constants.TRUE))) {
            userCode = userInfoHelper.getUserCode();
            if (StringUtil.isNotBlank(userCode)) {
                final UserInfo userInfo = new UserInfo();
                userInfo.setCode(userCode);
                userInfo.setCreatedTime(now);
                userInfo.setUpdatedTime(now);
                searchLog.setUserInfo(OptionalEntity.of(userInfo));
            }
        }

        searchLog.setHitCount(queryResponseList.getAllRecordCount());
        searchLog.setResponseTime(Integer.valueOf((int) queryResponseList.getExecTime()));
        searchLog.setSearchWord(StringUtils.abbreviate(query, 1000));
        searchLog.setSearchQuery(StringUtils.abbreviate(queryResponseList.getSearchQuery(), 1000));
        searchLog.setSolrQuery(StringUtils.abbreviate(queryResponseList.getSolrQuery(), 1000));
        searchLog.setRequestedTime(now);
        searchLog.setQueryOffset(pageStart);
        searchLog.setQueryPageSize(pageNum);

        searchLog.setClientIp(StringUtils.abbreviate(request.getRemoteAddr(), 50));
        searchLog.setReferer(StringUtils.abbreviate(request.getHeader("referer"), 1000));
        searchLog.setUserAgent(StringUtils.abbreviate(request.getHeader("user-agent"), 255));
        if (userCode != null) {
            searchLog.setUserSessionId(userCode);
        }
        final Object accessType = request.getAttribute(Constants.SEARCH_LOG_ACCESS_TYPE);
        if (accessType instanceof CDef.AccessType) {
            switch ((CDef.AccessType) accessType) {
            case Json:
                searchLog.setAccessType_Json();
                searchLog.setAccessType_Others();
                searchLog.setAccessType_Xml();
                break;
            case Xml:
                searchLog.setAccessType_Xml();
                break;
            case Others:
                searchLog.setAccessType_Others();
                break;
            default:
                searchLog.setAccessType_Web();
                break;
            }
        } else {
            searchLog.setAccessType_Web();
        }

        @SuppressWarnings("unchecked")
        final Map<String, List<String>> fieldLogMap = (Map<String, List<String>>) request
                .getAttribute(Constants.FIELD_LOGS);
        if (fieldLogMap != null) {
            for (final Map.Entry<String, List<String>> logEntry : fieldLogMap.entrySet()) {
                for (final String value : logEntry.getValue()) {
                    searchLog.addSearchFieldLogValue(logEntry.getKey(), StringUtils.abbreviate(value, 1000));
                }
            }
        }

        searchLogHelper.addSearchLog(searchLog);
    }

    final String[] highlightQueries = (String[]) request.getAttribute(Constants.HIGHLIGHT_QUERIES);
    if (highlightQueries != null) {
        final StringBuilder buf = new StringBuilder(100);
        for (final String q : highlightQueries) {
            buf.append("&hq=").append(q);
        }
        appendHighlightQueries = buf.toString();
    }

    Beans.copy(documentItems, this)
            .includes("pageSize", "currentPageNumber", "allRecordCount", "allPageCount", "existNextPage",
                    "existPrevPage", "currentStartRecordNumber", "currentEndRecordNumber", "pageNumberList",
                    "partialResults", "queryTime", "searchTime")
            .execute();

    return query;
}