Example usage for org.springframework.expression.common LiteralExpression LiteralExpression

List of usage examples for org.springframework.expression.common LiteralExpression LiteralExpression

Introduction

In this page you can find the example usage for org.springframework.expression.common LiteralExpression LiteralExpression.

Prototype

public LiteralExpression(String literalValue) 

Source Link

Usage

From source file:fr.xebia.management.statistics.ProfileAspect.java

@Around(value = "execution(* *(..)) && @annotation(profiled)", argNames = "pjp,profiled")
public Object profileInvocation(ProceedingJoinPoint pjp, Profiled profiled) throws Throwable {

    logger.trace("> profileInvocation({},{}", pjp, profiled);

    MethodSignature jointPointSignature = (MethodSignature) pjp.getStaticPart().getSignature();

    // COMPUTE SERVICE STATISTICS NAME
    Expression nameAsExpression = profiledMethodNameAsExpressionByMethod.get(jointPointSignature.getMethod());
    if (nameAsExpression == null) {
        if (StringUtils.hasLength(profiled.name())) {
            String nameAsStringExpression = profiled.name();
            nameAsExpression = expressionParser.parseExpression(nameAsStringExpression, parserContext);
        } else {/*from   w w w. j a va 2 s . c  o  m*/
            String fullyQualifiedMethodName = getFullyQualifiedMethodName(//
                    jointPointSignature.getDeclaringTypeName(), //
                    jointPointSignature.getName(), //
                    this.classNameStyle);
            nameAsExpression = new LiteralExpression(fullyQualifiedMethodName);
        }
    }

    String serviceStatisticsName;
    if (nameAsExpression instanceof LiteralExpression) {
        // Optimization : prevent useless objects instantiations
        serviceStatisticsName = nameAsExpression.getExpressionString();
    } else {
        serviceStatisticsName = nameAsExpression.getValue(new RootObject(pjp), String.class);
    }

    // LOOKUP SERVICE STATISTICS
    ServiceStatistics serviceStatistics = serviceStatisticsByName.get(serviceStatisticsName);

    if (serviceStatistics == null) {
        // INSTIANCIATE NEW SERVICE STATISTICS
        ServiceStatistics newServiceStatistics = new ServiceStatistics(//
                new ObjectName(this.jmxDomain + ":type=ServiceStatistics,name=" + serviceStatisticsName), //
                profiled.businessExceptionsTypes(), profiled.communicationExceptionsTypes());

        newServiceStatistics.setSlowInvocationThresholdInMillis(profiled.slowInvocationThresholdInMillis());
        newServiceStatistics
                .setVerySlowInvocationThresholdInMillis(profiled.verySlowInvocationThresholdInMillis());
        int maxActive;
        if (StringUtils.hasLength(profiled.maxActiveExpression())) {
            maxActive = expressionParser.parseExpression(profiled.maxActiveExpression(), parserContext)
                    .getValue(new RootObject(pjp), Integer.class);
        } else {
            maxActive = profiled.maxActive();
        }
        newServiceStatistics.setMaxActive(maxActive);
        newServiceStatistics.setMaxActiveSemaphoreAcquisitionMaxTimeInNanos(TimeUnit.NANOSECONDS
                .convert(profiled.maxActiveSemaphoreAcquisitionMaxTimeInMillis(), TimeUnit.MILLISECONDS));

        ServiceStatistics previousServiceStatistics = serviceStatisticsByName.putIfAbsent(serviceStatisticsName,
                newServiceStatistics);
        if (previousServiceStatistics == null) {
            serviceStatistics = newServiceStatistics;
            mbeanExporter.registerManagedResource(serviceStatistics);
        } else {
            serviceStatistics = previousServiceStatistics;
        }
    }

    // INVOKE AND PROFILE INVOCATION
    long nanosBefore = System.nanoTime();

    Semaphore semaphore = serviceStatistics.getMaxActiveSemaphore();
    if (semaphore != null) {
        boolean acquired = semaphore.tryAcquire(
                serviceStatistics.getMaxActiveSemaphoreAcquisitionMaxTimeInNanos(), TimeUnit.NANOSECONDS);
        if (!acquired) {
            serviceStatistics.incrementServiceUnavailableExceptionCount();
            throw new ServiceUnavailableException("Service '" + serviceStatisticsName + "' is unavailable: "
                    + serviceStatistics.getCurrentActive() + " invocations of are currently running");
        }
    }
    serviceStatistics.incrementCurrentActiveCount();
    try {

        Object returned = pjp.proceed();

        return returned;
    } catch (Throwable t) {
        serviceStatistics.incrementExceptionCount(t);
        throw t;
    } finally {
        if (semaphore != null) {
            semaphore.release();
        }
        serviceStatistics.decrementCurrentActiveCount();
        long deltaInNanos = System.nanoTime() - nanosBefore;
        serviceStatistics.incrementInvocationCounterAndTotalDurationWithNanos(deltaInNanos);
        if (logger.isDebugEnabled()) {
            logger.debug("< profileInvocation({}): {}ns", serviceStatisticsName, deltaInNanos);
        }
    }
}

From source file:org.springframework.integration.file.FileWritingMessageHandler.java

/**
 * Constructor which sets the {@link #destinationDirectoryExpression} using
 * a {@link LiteralExpression}./*  ww w .  j  a v  a 2  s. c o  m*/
 *
 * @param destinationDirectory Must not be null
 * @see #FileWritingMessageHandler(Expression)
 */
public FileWritingMessageHandler(File destinationDirectory) {
    Assert.notNull(destinationDirectory, "Destination directory must not be null.");
    this.destinationDirectoryExpression = new LiteralExpression(destinationDirectory.getPath());
}

From source file:org.springframework.integration.ftp.outbound.FtpOutboundTests.java

@Test
public void testHandleFileContentMessage() throws Exception {
    File file = new File("remote-target-dir/handlerContent.test");
    if (file.exists()) {
        file.delete();/* www.ja va  2 s.  c om*/
    }
    assertFalse(file.exists());
    FileTransferringMessageHandler<FTPFile> handler = new FileTransferringMessageHandler<FTPFile>(
            sessionFactory);
    handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir"));
    handler.setFileNameGenerator(new FileNameGenerator() {
        public String generateFileName(Message<?> message) {
            return "handlerContent.test";
        }
    });
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.handleMessage(new GenericMessage<String>("hello"));
    assertTrue(file.exists());
}

From source file:org.springframework.integration.ftp.outbound.FtpOutboundTests.java

@Test
public void testHandleFileAsByte() throws Exception {
    File file = new File("remote-target-dir/handlerContent.test");
    if (file.exists()) {
        file.delete();// w  w w  .  ja  v  a  2  s.  com
    }
    assertFalse(file.exists());
    FileTransferringMessageHandler<FTPFile> handler = new FileTransferringMessageHandler<FTPFile>(
            sessionFactory);
    handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir"));
    handler.setFileNameGenerator(new FileNameGenerator() {
        public String generateFileName(Message<?> message) {
            return "handlerContent.test";
        }
    });
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.handleMessage(new GenericMessage<byte[]>("hello".getBytes()));
    assertTrue(file.exists());
}

From source file:org.springframework.integration.ftp.outbound.FtpOutboundTests.java

@Test
public void testHandleFileMessage() throws Exception {
    File targetDir = new File("remote-target-dir");
    assertTrue("target directory does not exist: " + targetDir.getName(), targetDir.exists());

    FileTransferringMessageHandler<FTPFile> handler = new FileTransferringMessageHandler<FTPFile>(
            sessionFactory);//from www  .jav  a  2s  . c o  m
    handler.setRemoteDirectoryExpression(new LiteralExpression(targetDir.getName()));
    handler.setFileNameGenerator(new FileNameGenerator() {
        public String generateFileName(Message<?> message) {
            return ((File) message.getPayload()).getName() + ".test";
        }
    });
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();

    File srcFile = File.createTempFile("testHandleFileMessage", ".tmp");
    srcFile.deleteOnExit();

    File destFile = new File(targetDir, srcFile.getName() + ".test");
    destFile.deleteOnExit();

    handler.handleMessage(new GenericMessage<File>(srcFile));
    assertTrue("destination file was not created", destFile.exists());
}

From source file:org.springframework.integration.ftp.outbound.FtpSendingMessageHandlerTests.java

@Test
public void testHandleFileContentMessage() throws Exception {
    File file = new File("remote-target-dir/handlerContent.test");
    if (file.exists()) {
        file.delete();//from   www. j a  v a 2  s  . c  o  m
    }
    assertFalse(file.exists());
    FileTransferringMessageHandler<FTPFile> handler = new FileTransferringMessageHandler<FTPFile>(
            sessionFactory);
    handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir"));
    handler.setFileNameGenerator(new FileNameGenerator() {
        public String generateFileName(Message<?> message) {
            return "handlerContent.test";
        }
    });
    handler.afterPropertiesSet();
    handler.handleMessage(new GenericMessage<String>("hello"));
    assertTrue(file.exists());
}

From source file:org.springframework.integration.ftp.outbound.FtpSendingMessageHandlerTests.java

@Test
public void testHandleFileAsByte() throws Exception {
    File file = new File("remote-target-dir/handlerContent.test");
    if (file.exists()) {
        file.delete();//from   w  ww .j  a va2 s .  co  m
    }
    assertFalse(file.exists());
    FileTransferringMessageHandler<FTPFile> handler = new FileTransferringMessageHandler<FTPFile>(
            sessionFactory);
    handler.setRemoteDirectoryExpression(new LiteralExpression("remote-target-dir"));
    handler.setFileNameGenerator(new FileNameGenerator() {
        public String generateFileName(Message<?> message) {
            return "handlerContent.test";
        }
    });
    handler.afterPropertiesSet();
    handler.handleMessage(new GenericMessage<byte[]>("hello".getBytes()));
    assertTrue(file.exists());
}

From source file:org.springframework.integration.ftp.outbound.FtpSendingMessageHandlerTests.java

@Test
public void testHandleFileMessage() throws Exception {
    File targetDir = new File("remote-target-dir");
    assertTrue("target directory does not exist: " + targetDir.getName(), targetDir.exists());

    FileTransferringMessageHandler<FTPFile> handler = new FileTransferringMessageHandler<FTPFile>(
            sessionFactory);/*from   w  ww  .j a  v  a  2s  .  c  o m*/
    handler.setRemoteDirectoryExpression(new LiteralExpression(targetDir.getName()));
    handler.setFileNameGenerator(new FileNameGenerator() {
        public String generateFileName(Message<?> message) {
            return ((File) message.getPayload()).getName() + ".test";
        }
    });
    handler.afterPropertiesSet();

    File srcFile = File.createTempFile("testHandleFileMessage", ".tmp");
    srcFile.deleteOnExit();

    File destFile = new File(targetDir, srcFile.getName() + ".test");
    destFile.deleteOnExit();

    handler.handleMessage(new GenericMessage<File>(srcFile));
    assertTrue("destination file was not created", destFile.exists());
}

From source file:org.springframework.integration.ftp.session.FtpRemoteFileTemplateTests.java

@Test
public void testINT3412AppendStatRmdir() throws IOException {
    FtpRemoteFileTemplate template = new FtpRemoteFileTemplate(sessionFactory);
    DefaultFileNameGenerator fileNameGenerator = new DefaultFileNameGenerator();
    fileNameGenerator.setExpression("'foobar.txt'");
    template.setFileNameGenerator(fileNameGenerator);
    template.setRemoteDirectoryExpression(new LiteralExpression("foo/"));
    template.setUseTemporaryFileName(false);
    template.execute(session -> {/*from   w w w .  j a va  2 s  .c  o  m*/
        session.mkdir("foo/");
        return session.mkdir("foo/bar/");
    });
    template.append(new GenericMessage<String>("foo"));
    template.append(new GenericMessage<String>("bar"));
    assertTrue(template.exists("foo/foobar.txt"));
    template.executeWithClient((ClientCallbackWithoutResult<FTPClient>) client -> {
        try {
            FTPFile[] files = client.listFiles("foo/foobar.txt");
            assertEquals(6, files[0].getSize());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
    template.execute((SessionCallbackWithoutResult<FTPFile>) session -> {
        assertTrue(session.remove("foo/foobar.txt"));
        assertTrue(session.rmdir("foo/bar/"));
        FTPFile[] files = session.list("foo/");
        assertEquals(0, files.length);
        assertTrue(session.rmdir("foo/"));
    });
    assertFalse(template.getSession().exists("foo"));
}

From source file:org.springframework.integration.ftp.session.FtpRemoteFileTemplateTests.java

@Test
public void testFileCloseOnBadConnect() throws Exception {
    @SuppressWarnings("unchecked")
    SessionFactory<FTPFile> sessionFactory = mock(SessionFactory.class);
    when(sessionFactory.getSession()).thenThrow(new RuntimeException("bar"));
    FtpRemoteFileTemplate template = new FtpRemoteFileTemplate(sessionFactory);
    template.setRemoteDirectoryExpression(new LiteralExpression("foo"));
    template.afterPropertiesSet();//ww  w.  j a  v  a  2s.c  o m
    File file = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    fileOutputStream.write("foo".getBytes());
    fileOutputStream.close();
    try {
        template.send(new GenericMessage<File>(file));
        fail("exception expected");
    } catch (MessagingException e) {
        assertEquals("bar", e.getCause().getMessage());
    }
    File newFile = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    assertTrue(file.renameTo(newFile));
    file.delete();
    newFile.delete();
}