Example usage for org.springframework.util ResourceUtils getURL

List of usage examples for org.springframework.util ResourceUtils getURL

Introduction

In this page you can find the example usage for org.springframework.util ResourceUtils getURL.

Prototype

public static URL getURL(String resourceLocation) throws FileNotFoundException 

Source Link

Document

Resolve the given resource location to a java.net.URL .

Usage

From source file:org.alfresco.repo.audit.AuditBootstrapTest.java

@Override
public void setUp() throws Exception {
    auditModelRegistry = (AuditModelRegistryImpl) ctx.getBean("auditModel.modelRegistry");
    auditModelRegistry.setProperty(AuditModelRegistryImpl.PROPERTY_AUDIT_CONFIG_STRICT,
            Boolean.TRUE.toString());

    // Register a new model
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();
}

From source file:org.alfresco.repo.audit.AuditBootstrapTest.java

private void loadBadModel(String url) throws Exception {
    try {/*from   w  w w. ja va  2s  .  c  o m*/
        URL testModelUrl = ResourceUtils.getURL(url);
        auditModelRegistry.registerModel(testModelUrl);
        auditModelRegistry.loadAuditModels();
        fail("Expected model loading to fail.");
    } catch (AuditModelException e) {
        // Expected
        logger.error("Expected AuditModelException: " + e.getMessage());
    }
}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

@Override
public void setUp() throws Exception {
    auditModelRegistry = (AuditModelRegistryImpl) ctx.getBean("auditModel.modelRegistry");
    //MNT-10807 : Auditing does not take into account audit.filter.alfresco-access.transaction.user
    UserAuditFilter userAuditFilter = new UserAuditFilter();
    userAuditFilter.setUserFilterPattern("~System;~null;.*");
    userAuditFilter.afterPropertiesSet();
    auditComponent = (AuditComponentImpl) ctx.getBean("auditComponent");
    auditComponent.setUserAuditFilter(userAuditFilter);
    serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    auditService = serviceRegistry.getAuditService();
    transactionService = serviceRegistry.getTransactionService();
    transactionServiceImpl = (TransactionServiceImpl) ctx.getBean("transactionService");
    nodeService = serviceRegistry.getNodeService();
    fileFolderService = serviceRegistry.getFileFolderService();

    // Register the test model
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();

    RunAsWork<NodeRef> testRunAs = new RunAsWork<NodeRef>() {
        public NodeRef doWork() throws Exception {
            return nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
        }/*  www .j a v  a2 s  .  c  om*/
    };
    nodeRef = AuthenticationUtil.runAs(testRunAs, AuthenticationUtil.getSystemUserName());

    // Authenticate
    user = "User-" + getName();
    AuthenticationUtil.setFullyAuthenticatedUser(user);

    final RetryingTransactionCallback<Void> resetDisabledPathsCallback = new RetryingTransactionCallback<Void>() {
        public Void execute() throws Throwable {
            auditComponent.resetDisabledPaths(APPLICATION_TEST);
            auditComponent.resetDisabledPaths(APPLICATION_ACTIONS_TEST);
            return null;
        }
    };
    transactionService.getRetryingTransactionHelper().doInTransaction(resetDisabledPathsCallback);
}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

public void testAuditAuthenticationService() throws Exception {
    AuditQueryParameters params = new AuditQueryParameters();
    params.setForward(true);//from   ww  w . j  a  va2s .  c  om
    params.setApplicationName(APPLICATION_API_TEST);

    // Load in the config for this specific test: alfresco-audit-test-authenticationservice.xml
    URL testModelUrl = ResourceUtils
            .getURL("classpath:alfresco/testaudit/alfresco-audit-test-authenticationservice.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();

    final List<Long> results = new ArrayList<Long>(5);
    final StringBuilder sb = new StringBuilder();
    AuditQueryCallback auditQueryCallback = new AuditQueryCallback() {
        public boolean valuesRequired() {
            return true;
        }

        public boolean handleAuditEntry(Long entryId, String applicationName, String user, long time,
                Map<String, Serializable> values) {
            results.add(entryId);
            if (logger.isDebugEnabled()) {
                logger.debug("Audit Entry " + entryId + ": " + applicationName + ", " + user + ", "
                        + new Date(time) + "\n" + "   Data: " + values);
            }
            sb.append("Row: ").append(entryId).append(" | ").append(applicationName).append(" | ").append(user)
                    .append(" | ").append(new Date(time)).append(" | ").append(values).append(" | ")
                    .append("\n");
            ;
            return true;
        }

        public boolean handleAuditEntryError(Long entryId, String errorMsg, Throwable error) {
            throw new AlfrescoRuntimeException(errorMsg, error);
        }
    };

    clearAuditLog(APPLICATION_API_TEST);
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    logger.debug(sb.toString());
    assertTrue("There should be no audit entries for the API test after a clear", results.isEmpty());

    final MutableAuthenticationService authenticationService = serviceRegistry.getAuthenticationService();
    // Create a good authentication
    RunAsWork<Void> createAuthenticationWork = new RunAsWork<Void>() {
        public Void doWork() throws Exception {
            if (!authenticationService.authenticationExists(getName())) {
                authenticationService.createAuthentication(getName(), getName().toCharArray());
            }
            return null;
        }
    };
    AuthenticationUtil.runAs(createAuthenticationWork, AuthenticationUtil.getSystemUserName());

    // Clear everything out and do a successful authentication
    clearAuditLog(APPLICATION_API_TEST);
    try {
        AuthenticationUtil.pushAuthentication();
        authenticationService.authenticate(getName(), getName().toCharArray());
    } finally {
        AuthenticationUtil.popAuthentication();
    }

    // Check that the call was audited
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    logger.debug(sb.toString());
    assertFalse("Did not get any audit results after successful login", results.isEmpty());

    // Clear everything and check that unsuccessful authentication was audited
    clearAuditLog(APPLICATION_API_TEST);
    int iterations = 1000;
    for (int i = 0; i < iterations; i++) {
        try {
            AuthenticationUtil.pushAuthentication();
            authenticationService.authenticate("banana", "****".toCharArray());
            fail("Invalid authentication attempt should fail");
        } catch (AuthenticationException e) {
            // Expected
        } finally {
            AuthenticationUtil.popAuthentication();
        }
    }

    // ALF-3055 : auditing of failures is now asynchronous, so loop up to 60 times with
    // a 5 second sleep to ensure that the audit is processed
    for (int i = 0; i < 60; i++) {
        results.clear();
        sb.delete(0, sb.length());
        queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
        if (results.size() == iterations) {
            break;
        }
        Thread.sleep(5000);
    }

    logger.debug(sb.toString());
    assertEquals("Incorrect number of audit entries after failed login", iterations, results.size());

    // Check that we can delete explicit entries
    long before = System.currentTimeMillis();
    deleteAuditEntries(results);
    System.out.println("Clearing " + results.size() + " entries by ID took "
            + (System.currentTimeMillis() - before) + "ms.");
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    logger.debug(sb.toString());
    assertEquals("Explicit audit entries were not deleted", 0, results.size());
}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

/**
 * See <a href="https://issues.alfresco.com/jira/browse/ALF-12638">ALF-12638</a>
 */// w  ww. j a  va 2s.  c o m
public void testAuditFailedNodeAccess() throws Exception {
    AuditQueryParameters params = new AuditQueryParameters();
    params.setForward(true);
    params.setApplicationName(APPLICATION_ALF12638_TEST);

    // Load in the config for this specific test: alfresco-audit-test-authenticationservice.xml
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-alf-12638.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();

    // There should be a log entry for the application
    final List<Long> results = new ArrayList<Long>(5);
    final StringBuilder sb = new StringBuilder();
    AuditQueryCallback auditQueryCallback = new AuditQueryCallback() {
        public boolean valuesRequired() {
            return true;
        }

        public boolean handleAuditEntry(Long entryId, String applicationName, String user, long time,
                Map<String, Serializable> values) {
            results.add(entryId);
            sb.append("Row: ").append(entryId).append(" | ").append(applicationName).append(" | ").append(user)
                    .append(" | ").append(new Date(time)).append(" | ").append(values).append(" | ")
                    .append("\n");
            ;
            return true;
        }

        public boolean handleAuditEntryError(Long entryId, String errorMsg, Throwable error) {
            throw new AlfrescoRuntimeException(errorMsg, error);
        }
    };

    clearAuditLog(APPLICATION_ALF12638_TEST);
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    assertTrue("There should be no audit entries for the API test after a clear", results.isEmpty());

    try {
        nodeService.getRootNode(new StoreRef("system://system"));
        fail("Should not be allowed to get 'system://system'");
    } catch (AccessDeniedException e) {
        // Expected
    }
    // Try this for a while until we get a result
    boolean success = false;
    for (int i = 0; i < 30; i++) {
        queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
        if (results.size() > 1) {
            logger.debug(sb.toString());
            success = true;
            break;
        }
        synchronized (this) {
            try {
                this.wait(1000L);
            } catch (InterruptedException e) {
            }
        }
    }
    assertTrue("There should be exactly one audit entry for the API test", success);
}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

/**
 * Test for MNT-10070 and MNT-14136//from   ww  w. j  a va 2  s .c  om
 */
public void testApplication() throws Exception {
    // Register the test model
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-mnt-10070.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();

    auditModelRegistry.setProperty("audit.enabled", "true");

    auditModelRegistry.setProperty("audit.app1.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app1.default.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app1.login.user", "~System;~null;.*");

    auditModelRegistry.setProperty("audit.app2.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app2.default.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app2.login.user", "~System;~null;~admin;.*");

    auditModelRegistry.setProperty("audit.app3.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app3.default.enabled", "true");
    auditModelRegistry.setProperty("audit.filter.app3.login.user", "~System;~null;.*");

    auditModelRegistry.afterPropertiesSet();

    AuthenticationUtil.setRunAsUserSystem();
    AuditApplication applicationOne = auditModelRegistry.getAuditApplicationByName(APPLICATION_ONE);
    assertNotNull("Application 'app1' dosn't exist", applicationOne);
    AuditApplication applicationTwo = auditModelRegistry.getAuditApplicationByName(APPLICATION_TWO);
    assertNotNull("Application 'app2' dosn't exist", applicationTwo);
    AuditApplication applicationThree = auditModelRegistry.getAuditApplicationByName(APPLICATION_THREE);
    assertNotNull("Application 'app3' dosn't exist", applicationThree);

    // auditComponent
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    PropertyAuditFilter filter = new PropertyAuditFilter();
    Properties properties = new Properties();
    properties.put("audit.enabled", "true");

    properties.put("audit.app1.enabled", "true");
    properties.put("audit.filter.app1.default.enabled", "true");
    properties.put("audit.filter.app1.default.user", "~System;~null;.*");

    properties.put("audit.app2.enabled", "true");
    properties.put("audit.filter.app2.default.enabled", "true");
    properties.put("audit.filter.app2.default.user", "~System;~null;~admin;.*");

    properties.put("audit.app3.enabled", "true");
    properties.put("audit.filter.app3.default.enabled", "true");
    properties.put("audit.filter.app3.default.user", "~System;~null;.*");

    filter.setProperties(properties);
    auditComponent.setAuditFilter(filter);

    Map<String, Serializable> auditMap = new HashMap<String, Serializable>();
    auditMap.put("/transaction/user", AuthenticationUtil.getFullyAuthenticatedUser());
    auditMap.put("/transaction/action", "CREATE");
    auditMap.put("/transaction/type", "cm:content");

    Map<String, Serializable> recordedAuditMap = auditComponent.recordAuditValues("/alfresco-access", auditMap);

    assertFalse("Audit values is empty.", recordedAuditMap.isEmpty());

    Map<String, Serializable> expected = new HashMap<String, Serializable>();
    // There should not be app2
    expected.put("/" + APPLICATION_ONE + "/transaction/action", "CREATE");
    expected.put("/" + APPLICATION_THREE + "/transaction/type", "cm:content");

    String failure = EqualsHelper.getMapDifferenceReport(recordedAuditMap, expected);
    if (failure != null) {
        fail(failure);
    }
}

From source file:org.alfresco.repo.audit.AuditComponentTest.java

/**
  * See <a href="https://issues.alfresco.com/jira/browse/MNT-10767">MNT-10767</a>
  *//*from w  ww  . ja v  a2s .  c  om*/
public void testAuditSubordinateCall() throws Exception {
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    AuditQueryParameters params = new AuditQueryParameters();
    params.setForward(true);
    params.setApplicationName(APPLICATION_MNT10767_TEST);

    // Load in the config for this specific test: alfresco-audit-test-mnt-10767
    URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-mnt-10767.xml");
    auditModelRegistry.registerModel(testModelUrl);
    auditModelRegistry.loadAuditModels();
    // There should be a log entry for the application
    final List<Long> results = new ArrayList<Long>(5);
    final StringBuilder sb = new StringBuilder();
    AuditQueryCallback auditQueryCallback = new AuditQueryCallback() {
        public boolean valuesRequired() {
            return true;
        }

        public boolean handleAuditEntry(Long entryId, String applicationName, String user, long time,
                Map<String, Serializable> values) {
            results.add(entryId);
            sb.append("Row: ").append(entryId).append(" | ").append(applicationName).append(" | ").append(user)
                    .append(" | ").append(new Date(time)).append(" | ").append(values).append(" | ")
                    .append("\n");
            ;
            return true;
        }

        public boolean handleAuditEntryError(Long entryId, String errorMsg, Throwable error) {
            throw new AlfrescoRuntimeException(errorMsg, error);
        }
    };

    clearAuditLog(APPLICATION_MNT10767_TEST);
    results.clear();
    sb.delete(0, sb.length());
    queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
    assertTrue("There should be no audit entries for the API test after a clear", results.isEmpty());

    PolicyComponent policyComponent = (PolicyComponent) ctx.getBean("policyComponent");
    policyComponent.bindClassBehaviour(OnCreateNodePolicy.QNAME, ContentModel.TYPE_FOLDER,
            new JavaBehaviour(this, "onCreateFolderMNT10767"));

    NodeRef workingRootNodeRef = null;
    try {
        workingRootNodeRef = nodeService
                .createNode(nodeRef, ContentModel.ASSOC_CHILDREN,
                        QName.createQName(NamespaceService.ALFRESCO_URI,
                                "working_root" + System.currentTimeMillis()),
                        ContentModel.TYPE_FOLDER)
                .getChildRef();

        // Try this for a while until we get a result
        boolean success = false;
        for (int i = 0; i < 30; i++) {
            queryAuditLog(auditQueryCallback, params, Integer.MAX_VALUE);
            if (results.size() > 1) {
                logger.debug(sb.toString());
                success = true;
                break;
            }
            synchronized (this) {
                try {
                    this.wait(1000L);
                } catch (InterruptedException e) {
                }
            }
        }
        assertTrue("There should be audit entry for the API test", success);
    } finally {
        if (workingRootNodeRef != null) {
            nodeService.deleteNode(workingRootNodeRef);
        }
    }
}

From source file:org.alfresco.repo.audit.AuditMethodInterceptorTest.java

@Override
public void setUp() throws Exception {
    auditModelRegistry = (AuditModelRegistryImpl) ctx.getBean("auditModel.modelRegistry");
    serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    auditComponent = (AuditComponent) ctx.getBean("auditComponent");
    auditService = serviceRegistry.getAuditService();
    transactionService = serviceRegistry.getTransactionService();
    transactionServiceImpl = (TransactionServiceImpl) ctx.getBean("transactionService");
    nodeService = serviceRegistry.getNodeService();

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    nodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);

    // Register the model
    URL modelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-mnt-11072.xml");
    auditModelRegistry.registerModel(modelUrl);
    auditModelRegistry.loadAuditModels();
}

From source file:org.alfresco.repo.audit.model.AuditModelRegistryImpl.java

/**
 * Unmarshalls the Audit model from a stream.
 *///from w w w. j  a va2  s  . co  m
private static Audit unmarshallModel(InputStream is, final String source) {
    final Schema schema;
    final JAXBContext jaxbCtx;
    final Unmarshaller jaxbUnmarshaller;
    try {
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = sf.newSchema(ResourceUtils.getURL(AUDIT_SCHEMA_LOCATION));
        jaxbCtx = JAXBContext.newInstance("org.alfresco.repo.audit.model._3");
        jaxbUnmarshaller = jaxbCtx.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        jaxbUnmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent ve) {
                if (ve.getSeverity() == ValidationEvent.FATAL_ERROR
                        || ve.getSeverity() == ValidationEvent.ERROR) {
                    ValidationEventLocator locator = ve.getLocator();
                    logger.error("Invalid Audit XML: \n" + "   Source:   " + source + "\n"
                            + "   Location: Line " + locator.getLineNumber() + " column "
                            + locator.getColumnNumber() + "\n" + "   Error:    " + ve.getMessage());
                }
                return false;
            }
        });
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Failed to load Alfresco Audit Schema from " + AUDIT_SCHEMA_LOCATION,
                e);
    }
    try {
        // Unmarshall with validation
        @SuppressWarnings("unchecked")
        JAXBElement<Audit> auditElement = (JAXBElement<Audit>) jaxbUnmarshaller.unmarshal(is);

        Audit audit = auditElement.getValue();
        // Done
        return audit;
    } catch (Throwable e) {
        // Dig out a SAXParseException, if there is one
        Throwable saxError = ExceptionStackUtil.getCause(e, SAXParseException.class);
        if (saxError != null) {
            e = saxError;
        }
        throw new AuditModelException("Failed to read Audit model XML: \n" + "   Source: " + source + "\n"
                + "   Error:  " + e.getMessage());
    } finally {
        try {
            is.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.geoserver.security.iride.service.policy.handler.request.IridePolicyRequestHandlerTest.java

/**
 *
 * @param handler//from  w  w w  .j av  a 2  s.co m
 * @return
 */
private IridePolicyRequestHandler prepareHandler(IridePolicyRequestHandler handler) {
    final HttpPostBuilder spied = spy(handler.getHttpPostBuilder());

    when(spied.build(eq(serverURL), anyString(), org.mockito.Matchers.any(Header[].class)))
            .then(new Answer<PostMethod>() {

                /*
                 * (non-Javadoc)
                 * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
                 */
                @Override
                public PostMethod answer(final InvocationOnMock invocation) throws Throwable {
                    return new PostMethod() {

                        /*
                         * (non-Javadoc)
                         * @see org.apache.commons.httpclient.methods.PostMethod#getName()
                         */
                        @Override
                        public String getName() {
                            return "FileMethod";
                        }

                        /*
                         * (non-Javadoc)
                         * @see org.apache.commons.httpclient.HttpMethodBase#getResponseBodyAsString()
                         */
                        @Override
                        public String getResponseBodyAsString() throws IOException {
                            final String resourceLocation = String.format(RESOURCE_LOCATION_PATTERN,
                                    IridePolicyRequestHandlerTest.this.policy.getServiceName());
                            try (final InputStream in = ResourceUtils.getURL(resourceLocation).openStream()) {
                                return IOUtils.toString(in);
                            }
                        }
                    };
                }
            });

    handler.setHttpPostBuilder(spied);

    return handler;
}