Java Examples for org.springframework.core.io.ByteArrayResource

The following java examples will help you to understand the usage of org.springframework.core.io.ByteArrayResource. These source code samples are taken from different open source projects.

Example 1
Project: data-lifecycle-service-broker-master  File: PostgresScriptExecutor.java View source code
public void execute(String script, Map<String, Object> creds) throws SQLException {
    String username = (String) creds.get("username");
    String password = (String) creds.get("password");
    String uri = "jdbc:" + (String) creds.get("uri");
    log.info("Sanitizing " + uri + " " + " as " + username);
    Connection connection = DriverManager.getConnection(uri, username, password);
    ScriptUtils.executeSqlScript(connection, new ByteArrayResource(script.getBytes()));
}
Example 2
Project: Katari-master  File: ConditionalImportParserTest.java View source code
@Test
public void testImportTrueCondition() {
    final String beans = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<beans xmlns='http://www.springframework.org/schema/beans'\n" + "  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n" + "  xmlns:katari='http://www.globant.com/schema/katari'\n" + "  xsi:schemaLocation='http://www.springframework.org/schema/beans\n" + "    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd\n" + "    http://www.globant.com/schema/katari\n" + "    http://www.globant.com/schema/katari/katari.xsd'>\n" + "  <katari:properties name='katari.props'" + "   location='classpath:/com/globant/katari/core/spring/test.properties'/>\n" + "  <katari:import properties-ref='katari.props'" + "    module='com.globant.katari.core.spring'\n" + "    property-name='authentication.mode' property-value='CAS'/>" + "</beans>\n";
    AbstractXmlApplicationContext context;
    context = new AbstractXmlApplicationContext() {

        protected Resource[] getConfigResources() {
            return new Resource[] { new ByteArrayResource(beans.getBytes()) };
        }
    };
    context.refresh();
    Object menubar = context.getBean("menubar");
    assertThat(menubar, is(MenuBar.class));
    context.close();
}
Example 3
Project: saos-master  File: SearchConfigurationFilesUtilsTest.java View source code
@Test
public void copyResource() throws IOException {
    File tmpDir = Files.createTempDir();
    File targetFile = new File(tmpDir, "someFile.txt");
    Resource resource = new ByteArrayResource("some resource".getBytes());
    SearchConfigurationFilesUtils.copyResource(resource, targetFile);
    assertFile(targetFile, "some resource");
    FileUtils.deleteDirectory(tmpDir);
}
Example 4
Project: Activiti-master  File: AbstractAutoDeploymentStrategy.java View source code
/**
     * Determines the name to be used for the provided resource.
     *
     * @param resource the resource to get the name for
     * @return the name of the resource
     */
protected String determineResourceName(final Resource resource) {
    String resourceName = null;
    if (resource instanceof ContextResource) {
        resourceName = ((ContextResource) resource).getPathWithinContext();
    } else if (resource instanceof ByteArrayResource) {
        resourceName = resource.getDescription();
    } else {
        try {
            resourceName = resource.getFile().getAbsolutePath();
        } catch (IOException e) {
            resourceName = resource.getFilename();
        }
    }
    return resourceName;
}
Example 5
Project: alf.io-master  File: TemplateManager.java View source code
public String renderTemplate(Event event, TemplateResource templateResource, Map<String, Object> model, Locale locale) {
    return uploadedResourceManager.findCascading(event.getOrganizationId(), event.getId(), templateResource.getSavedName(locale)).map( resource -> render(new ByteArrayResource(resource), model, locale, templateResource.getTemplateOutput())).orElseGet(() -> renderTemplate(templateResource, model, locale));
}
Example 6
Project: aws-flow-maven-eclipse-samples-master  File: DeploymentWorkflowImpl.java View source code
@Override
public Promise<String> deploy(String springTemplate) {
    Resource templateResource = new ByteArrayResource(springTemplate.getBytes());
    GenericXmlApplicationContext appContext = new GenericXmlApplicationContext();
    appContext.setParent(applicationContext);
    appContext.load(templateResource);
    appContext.refresh();
    ApplicationStack applicationStack = appContext.getBean("applicationStack", ApplicationStack.class);
    applicationStack.deploy();
    return applicationStack.getUrl();
}
Example 7
Project: BoxMeBackend-master  File: DeploymentWorkflowImpl.java View source code
@Override
public Promise<String> deploy(String springTemplate) {
    Resource templateResource = new ByteArrayResource(springTemplate.getBytes());
    GenericXmlApplicationContext appContext = new GenericXmlApplicationContext();
    appContext.setParent(applicationContext);
    appContext.load(templateResource);
    appContext.refresh();
    ApplicationStack applicationStack = appContext.getBean("applicationStack", ApplicationStack.class);
    applicationStack.deploy();
    return applicationStack.getUrl();
}
Example 8
Project: helium-master  File: MailDao.java View source code
public void send(String fromAddress, List<String> recipients, List<String> ccRecipients, List<String> bccRecipients, String subject, String text, List<ArxiuDto> attachments) throws Exception {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    mimeMessage.setFrom(new InternetAddress(fromAddress));
    if (recipients != null) {
        for (String recipient : recipients) {
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        }
    }
    if (ccRecipients != null) {
        for (String recipient : ccRecipients) {
            mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(recipient));
        }
    }
    if (bccRecipients != null) {
        for (String recipient : bccRecipients) {
            mimeMessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(recipient));
        }
    }
    mimeMessage.setSubject(subject);
    if (attachments != null) {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        for (ArxiuDto arxiu : attachments) {
            helper.addAttachment(arxiu.getNom(), new ByteArrayResource(arxiu.getContingut()));
        }
        helper.setText(text);
    } else {
        mimeMessage.setText(text);
    }
    this.mailSender.send(mimeMessage);
}
Example 9
Project: march4-master  File: DeploymentWorkflowImpl.java View source code
@Override
public Promise<String> deploy(String springTemplate) {
    Resource templateResource = new ByteArrayResource(springTemplate.getBytes());
    GenericXmlApplicationContext appContext = new GenericXmlApplicationContext();
    appContext.setParent(applicationContext);
    appContext.load(templateResource);
    appContext.refresh();
    ApplicationStack applicationStack = appContext.getBean("applicationStack", ApplicationStack.class);
    applicationStack.deploy();
    return applicationStack.getUrl();
}
Example 10
Project: medusa-glacier-master  File: DeploymentWorkflowImpl.java View source code
@Override
public Promise<String> deploy(String springTemplate) {
    Resource templateResource = new ByteArrayResource(springTemplate.getBytes());
    GenericXmlApplicationContext appContext = new GenericXmlApplicationContext();
    appContext.setParent(applicationContext);
    appContext.load(templateResource);
    appContext.refresh();
    ApplicationStack applicationStack = appContext.getBean("applicationStack", ApplicationStack.class);
    applicationStack.deploy();
    return applicationStack.getUrl();
}
Example 11
Project: mina-ftpserver-master  File: SpringConfigTestTemplate.java View source code
protected FtpServer createServer(String config) {
    String completeConfig = "<server id=\"server\" xmlns=\"http://mina.apache.org/ftpserver/spring/v1\" " + "xmlns:beans=\"http://www.springframework.org/schema/beans\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:schemaLocation=\" " + "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd " + "http://mina.apache.org/ftpserver/spring/v1 http://mina.apache.org/ftpserver/ftpserver-1.0.xsd " + "\">" + config + "</server>";
    XmlBeanFactory factory = new XmlBeanFactory(new ByteArrayResource(completeConfig.getBytes()));
    return (FtpServer) factory.getBean("server");
}
Example 12
Project: opennms_dashboard-master  File: OpenNMSTestCase.java View source code
protected void setUp() throws Exception {
    super.setUp();
    MockUtil.println("------------ Begin Test " + this + " --------------------------");
    MockLogAppender.setupLogging();
    if (m_runSupers) {
        createMockNetwork();
        populateDatabase();
        DataSourceFactory.setInstance(m_db);
        SnmpPeerFactory.setInstance(new SnmpPeerFactory(new ByteArrayResource(getSnmpConfig().getBytes())));
        if (isStartEventd()) {
            m_eventdIpcMgr = new EventIpcManagerDefaultImpl();
            JdbcEventdServiceManager eventdServiceManager = new JdbcEventdServiceManager();
            eventdServiceManager.setDataSource(m_db);
            eventdServiceManager.afterPropertiesSet();
            /*
                 * Make sure we specify a full resource path since "this" is
                 * the unit test class, which is most likely in another package. 
                 */
            File configFile = ConfigurationTestUtils.getFileForResource(this, "/org/opennms/netmgt/mock/eventconf.xml");
            DefaultEventConfDao eventConfDao = new DefaultEventConfDao();
            eventConfDao.setConfigResource(new FileSystemResource(configFile));
            eventConfDao.afterPropertiesSet();
            EventconfFactory.setInstance(eventConfDao);
            EventExpander eventExpander = new EventExpander();
            eventExpander.setEventConfDao(eventConfDao);
            eventExpander.afterPropertiesSet();
            JdbcEventWriter jdbcEventWriter = new JdbcEventWriter();
            jdbcEventWriter.setEventdServiceManager(eventdServiceManager);
            jdbcEventWriter.setDataSource(m_db);
            // for HSQL: "SELECT max(eventId)+1 from events"
            jdbcEventWriter.setGetNextIdString("select nextVal('eventsNxtId')");
            jdbcEventWriter.afterPropertiesSet();
            EventIpcBroadcastProcessor eventIpcBroadcastProcessor = new EventIpcBroadcastProcessor();
            eventIpcBroadcastProcessor.setEventIpcBroadcaster(m_eventdIpcMgr);
            eventIpcBroadcastProcessor.afterPropertiesSet();
            List<EventProcessor> eventProcessors = new ArrayList<EventProcessor>(3);
            eventProcessors.add(eventExpander);
            eventProcessors.add(jdbcEventWriter);
            eventProcessors.add(eventIpcBroadcastProcessor);
            DefaultEventHandlerImpl eventHandler = new DefaultEventHandlerImpl();
            eventHandler.setEventProcessors(eventProcessors);
            eventHandler.afterPropertiesSet();
            m_eventdIpcMgr.setHandlerPoolSize(5);
            m_eventdIpcMgr.setEventHandler(eventHandler);
            m_eventdIpcMgr.afterPropertiesSet();
            m_eventProxy = m_eventdIpcMgr;
            EventIpcManagerFactory.setIpcManager(m_eventdIpcMgr);
            EventIpcManagerEventHandlerProxy proxy = new EventIpcManagerEventHandlerProxy();
            proxy.setEventIpcManager(m_eventdIpcMgr);
            proxy.afterPropertiesSet();
            List<EventHandler> eventHandlers = new ArrayList<EventHandler>(1);
            eventHandlers.add(proxy);
            TcpEventReceiver tcpEventReceiver = new TcpEventReceiver();
            tcpEventReceiver.setPort(5837);
            tcpEventReceiver.setEventHandlers(eventHandlers);
            UdpEventReceiver udpEventReceiver = new UdpEventReceiver();
            udpEventReceiver.setPort(5837);
            tcpEventReceiver.setEventHandlers(eventHandlers);
            List<EventReceiver> eventReceivers = new ArrayList<EventReceiver>(2);
            eventReceivers.add(tcpEventReceiver);
            eventReceivers.add(udpEventReceiver);
            m_eventd = new Eventd();
            m_eventd.setEventdServiceManager(eventdServiceManager);
            m_eventd.setEventReceivers(eventReceivers);
            m_eventd.setReceiver(new BroadcastEventProcessor(m_eventdIpcMgr, eventConfDao));
            m_eventd.init();
            m_eventd.start();
        }
    }
    m_transMgr = new DataSourceTransactionManager(DataSourceFactory.getInstance());
}
Example 13
Project: piggy-master  File: EmailServiceImpl.java View source code
@Override
public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException {
    final String subject = env.getProperty(type.getSubject());
    final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName());
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(recipient.getEmail());
    helper.setSubject(subject);
    helper.setText(text);
    if (StringUtils.hasLength(attachment)) {
        helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes()));
    }
    mailSender.send(message);
    log.info("{} email notification has been send to {}", type, recipient.getEmail());
}
Example 14
Project: PiggyMetrics-master  File: EmailServiceImpl.java View source code
@Override
public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException {
    final String subject = env.getProperty(type.getSubject());
    final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName());
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(recipient.getEmail());
    helper.setSubject(subject);
    helper.setText(text);
    if (StringUtils.hasLength(attachment)) {
        helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes()));
    }
    mailSender.send(message);
    log.info("{} email notification has been send to {}", type, recipient.getEmail());
}
Example 15
Project: smsc-server-master  File: SpringConfigTestTemplate.java View source code
protected SmscServer createServer(String config) {
    String completeConfig = //
    "<server id=\"server\" xmlns=\"http://mina.apache.org/smscserver/spring/v1\" " + //
    "xmlns:beans=\"http://www.springframework.org/schema/beans\" " + //
    "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + //
    "xsi:schemaLocation=\" " + //
    "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd " + //
    "http://mina.apache.org/smscserver/spring/v1 http://mina.apache.org/smscserver/smscserver-1.0.xsd " + //
    "\">" + config + "</server>";
    XmlBeanFactory factory = new XmlBeanFactory(new ByteArrayResource(completeConfig.getBytes()));
    return (SmscServer) factory.getBean("server");
}
Example 16
Project: spring-batch-master  File: StaxEventItemReaderTests.java View source code
@Test
public void testFragmentNamespace() throws Exception {
    source.setResource(new ByteArrayResource(fooXml.getBytes()));
    source.afterPropertiesSet();
    source.open(executionContext);
    // see asserts in the mock unmarshaller
    assertNotNull(source.read());
    assertNotNull(source.read());
    // there are only two fragments
    assertNull(source.read());
    source.close();
}
Example 17
Project: spring-boot-master  File: ConfigFileApplicationListenerTests.java View source code
@Override
public Resource getResource(final String location) {
    if (location.equals("classpath:/custom.properties")) {
        return new ByteArrayResource("the.property: fromcustom".getBytes(), location) {

            @Override
            public String getFilename() {
                return location;
            }
        };
    }
    return null;
}
Example 18
Project: spring-data-rest-master  File: TestUtils.java View source code
/**
	 * Filters the given {@link Resource} by replacing values within.
	 * 
	 * @param source must not be {@literal null}.
	 * @param replacements
	 * @return {@link Resource} with replaced values.
	 * @throws IOException
	 */
public static Resource filterResource(Resource source, Map<String, ?> replacements) throws IOException {
    Assert.notNull(source, "Cannot filter 'null' resource");
    if (CollectionUtils.isEmpty(replacements)) {
        return source;
    }
    String temp = StreamUtils.copyToString(source.getInputStream(), UTF8);
    for (Map.Entry<String, ?> entry : replacements.entrySet()) {
        temp = StringUtils.replace(temp, entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : "");
    }
    return new ByteArrayResource(temp.getBytes(UTF8));
}
Example 19
Project: spring-integration-master  File: XsltPayloadTransformerTests.java View source code
private Resource getXslResource() throws Exception {
    String xsl = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + "   <xsl:template match=\"order\">" + "     <bob>test</bob>" + "   </xsl:template>" + "</xsl:stylesheet>";
    return new ByteArrayResource(xsl.getBytes("UTF-8"));
}
Example 20
Project: spring-reactive-master  File: ResourceEncoderTests.java View source code
@Test
public void canEncode() throws Exception {
    assertTrue(this.encoder.canEncode(ResolvableType.forClass(InputStreamResource.class), MediaType.TEXT_PLAIN));
    assertTrue(this.encoder.canEncode(ResolvableType.forClass(ByteArrayResource.class), MediaType.TEXT_PLAIN));
    assertTrue(this.encoder.canEncode(ResolvableType.forClass(Resource.class), MediaType.TEXT_PLAIN));
    assertTrue(this.encoder.canEncode(ResolvableType.forClass(InputStreamResource.class), MediaType.APPLICATION_JSON));
}
Example 21
Project: spring-rich-client-master  File: ScriptedViewTests.java View source code
public void testHappyPath() throws Exception {
    final ScriptEngine engine = EasyMock.createMock(ScriptEngine.class);
    ScriptedView scriptedView = new ScriptedView() {

        @Override
        protected ScriptEngine createScriptEngine() {
            return engine;
        }
    };
    EasyMock.expect(engine.createBindings()).andReturn(new SimpleBindings());
    engine.setContext((ScriptContext) EasyMock.anyObject());
    EasyMock.expect(engine.eval((Reader) EasyMock.anyObject())).andReturn(null);
    EasyMock.replay(engine);
    scriptedView.setEngineName("test-engine");
    scriptedView.setScript(new ByteArrayResource("test".getBytes(), "test script"));
    JComponent control = scriptedView.createControl();
    System.out.println(control);
    EasyMock.verify(engine);
}
Example 22
Project: springrcp-master  File: ScriptedViewTests.java View source code
public void testHappyPath() throws Exception {
    final ScriptEngine engine = EasyMock.createMock(ScriptEngine.class);
    ScriptedView scriptedView = new ScriptedView() {

        @Override
        protected ScriptEngine createScriptEngine() {
            return engine;
        }
    };
    EasyMock.expect(engine.createBindings()).andReturn(new SimpleBindings());
    engine.setContext((ScriptContext) EasyMock.anyObject());
    EasyMock.expect(engine.eval((Reader) EasyMock.anyObject())).andReturn(null);
    EasyMock.replay(engine);
    scriptedView.setEngineName("test-engine");
    scriptedView.setScript(new ByteArrayResource("test".getBytes(), "test script"));
    JComponent control = scriptedView.createControl();
    System.out.println(control);
    EasyMock.verify(engine);
}
Example 23
Project: ignite-master  File: IgniteSpringHelperImpl.java View source code
/** {@inheritDoc} */
@Override
public String userVersion(ClassLoader ldr, IgniteLogger log) {
    assert ldr != null;
    assert log != null;
    // For system class loader return cached version.
    if (ldr == U.gridClassLoader() && SYS_LDR_VER.get() != null)
        return SYS_LDR_VER.get();
    String usrVer = U.DFLT_USER_VERSION;
    InputStream in = ldr.getResourceAsStream(IGNITE_XML_PATH);
    if (in != null) {
        // Note: use ByteArrayResource instead of InputStreamResource because
        // InputStreamResource doesn't work.
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            U.copy(in, out);
            DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
            XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
            reader.loadBeanDefinitions(new ByteArrayResource(out.toByteArray()));
            usrVer = (String) factory.getBean("userVersion");
            usrVer = usrVer == null ? U.DFLT_USER_VERSION : usrVer.trim();
        } catch (NoSuchBeanDefinitionException ignored) {
            if (log.isInfoEnabled())
                log.info("User version is not explicitly defined (will use default version) [file=" + IGNITE_XML_PATH + ", clsLdr=" + ldr + ']');
            usrVer = U.DFLT_USER_VERSION;
        } catch (BeansException e) {
            U.error(log, "Failed to parse Spring XML file (will use default user version) [file=" + IGNITE_XML_PATH + ", clsLdr=" + ldr + ']', e);
            usrVer = U.DFLT_USER_VERSION;
        } catch (IOException e) {
            U.error(log, "Failed to read Spring XML file (will use default user version) [file=" + IGNITE_XML_PATH + ", clsLdr=" + ldr + ']', e);
            usrVer = U.DFLT_USER_VERSION;
        } finally {
            U.close(out, log);
        }
    }
    // For system class loader return cached version.
    if (ldr == U.gridClassLoader())
        SYS_LDR_VER.compareAndSet(null, usrVer);
    return usrVer;
}
Example 24
Project: jcaptcha-trunk-master  File: JcaptchaImageMacro.java View source code
public String execute(Map params, String body, RenderContext renderContext) throws MacroException {
    String config = body;
    Integer configHash = new Integer(config.hashCode());
    if (!engineRegistry.containsKey(configHash)) {
        try {
            Resource resource = new ByteArrayResource(config.getBytes());
            XmlBeanFactory bf = new XmlBeanFactory(resource);
            ImageCaptchaFactory factory = (ImageCaptchaFactory) bf.getBean("imageCaptchaFactory");
            GenericCaptchaEngine engine = new GenericCaptchaEngine(new ImageCaptchaFactory[] { factory });
            engineRegistry.put(configHash, engine);
        } catch (Throwable e) {
            throw new MacroException(e);
        }
    }
    try {
        if (renderContext instanceof PageContext) {
            PageContext pageContext = (PageContext) renderContext;
            params.put("space", pageContext.getSpaceKey());
            params.put("page", pageContext.getPageTitle());
            params.put("body", body);
            params.put("configHash", configHash);
        } else {
            throw new MacroException("Cannot render images without pagecontext");
        }
        Map contextMap = MacroUtils.defaultVelocityContext();
        contextMap.putAll(params);
        return VelocityUtils.getRenderedTemplate("/jcaptchaimage.vm", contextMap);
    } catch (Exception e) {
        throw new MacroException(e.getMessage(), e);
    }
}
Example 25
Project: Play--framework-Spring-module-master  File: PlayClassPathBeanDefinitionScanner.java View source code
/**
	 * The override, which searches through the play framework's classes, instead of using
	 * files (as Spring is trained to do).
	 */
@Override
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
    Logger.debug("Finding candidate components with base package: " + basePackage);
    Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
    try {
        for (ApplicationClass appClass : Play.classes.all()) {
            if (appClass.name.startsWith(basePackage)) {
                Logger.debug("Scanning class: " + appClass.name);
                AbstractResource res = null;
                if (Play.usePrecompiled) {
                    File f = Play.getFile("precompiled/java/" + (appClass.name.replace(".", "/")) + ".class");
                    res = new InputStreamResource(new FileInputStream(f));
                } else {
                    res = new ByteArrayResource(appClass.enhance());
                }
                MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(res);
                if (isCandidateComponent(metadataReader)) {
                    ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                    sbd.setSource(res);
                    if (isCandidateComponent(sbd)) {
                        candidates.add(sbd);
                    }
                }
            } else {
                Logger.trace("Skipped class: " + appClass.name + " -- wrong base package");
            }
        }
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
    }
    return candidates;
}
Example 26
Project: spring-db4o-master  File: ResourceStorageTest.java View source code
@Test
public void testOpen() {
    String uri = "resource";
    BinConfiguration binConfiguration = new BinConfiguration(uri, false, 0, false);
    byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };
    Resource resource = new ByteArrayResource(bytes);
    ResourceLoader resourceLoader = mock(ResourceLoader.class);
    when(resourceLoader.getResource(uri)).thenReturn(resource);
    ResourceStorage resourceStorage = new ResourceStorage();
    resourceStorage.setResourceLoader(resourceLoader);
    Bin bin = resourceStorage.open(binConfiguration);
    Assert.assertEquals(bin.length(), bytes.length);
}
Example 27
Project: spring-framework-master  File: HttpEntityMethodProcessorMockTests.java View source code
@Test
public void shouldHandleResource() throws Exception {
    ResponseEntity<Resource> returnValue = ResponseEntity.ok(new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8)));
    given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true);
    given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
    given(resourceMessageConverter.canWrite(ByteArrayResource.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(true);
    processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest);
    then(resourceMessageConverter).should(times(1)).write(any(ByteArrayResource.class), eq(MediaType.APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
    assertEquals(200, servletResponse.getStatus());
}
Example 28
Project: spring-ldap-master  File: AbstractLdapTemplateIntegrationTest.java View source code
@Before
public void cleanAndSetup() throws NamingException, IOException {
    Resource ldifResource = getLdifFileResource();
    if (!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(DEFAULT_BASE))) {
        List<String> lines = IOUtils.readLines(ldifResource.getInputStream());
        StringWriter sw = new StringWriter();
        PrintWriter writer = new PrintWriter(sw);
        for (String line : lines) {
            writer.println(StringUtils.replace(line, DEFAULT_BASE, base));
        }
        writer.flush();
        ldifResource = new ByteArrayResource(sw.toString().getBytes("UTF8"));
    }
    LdapTestUtils.cleanAndSetup(contextSource, getRoot(), ldifResource);
}
Example 29
Project: spring-ws-test-master  File: FreeMarkerTemplateProcessor.java View source code
public Resource processTemplate(Resource resource, WebServiceMessage message) throws IOException {
    try {
        Configuration configuration = configurationFactory.createConfiguration();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.putAll(WsTestContextHolder.getTestContext().getAttributeMap());
        if (message != null) {
            properties.put("request", getXmlUtil().loadDocument(message));
        }
        properties.put("IGNORE", "${IGNORE}");
        StringWriter out = new StringWriter();
        configuration.getTemplate(resource.getURL().toString()).process(properties, out);
        return new ByteArrayResource(out.toString().getBytes("UTF-8"));
    } catch (TemplateException e) {
        throw new IllegalStateException("FreeMarker exception", e);
    }
}
Example 30
Project: uaa-master  File: BootstrapSamlIdentityProviderConfiguratorTests.java View source code
public static Map<String, Map<String, Object>> parseYaml(String sampleYaml) {
    YamlMapFactoryBean factory = new YamlMapFactoryBean();
    factory.setResolutionMethod(YamlProcessor.ResolutionMethod.OVERRIDE_AND_IGNORE);
    List<Resource> resources = new ArrayList<>();
    ByteArrayResource resource = new ByteArrayResource(sampleYaml.getBytes());
    resources.add(resource);
    factory.setResources(resources.toArray(new Resource[resources.size()]));
    Map<String, Object> tmpdata = factory.getObject();
    Map<String, Map<String, Object>> dataMap = new HashMap<>();
    for (Map.Entry<String, Object> entry : ((Map<String, Object>) tmpdata.get("providers")).entrySet()) {
        dataMap.put(entry.getKey(), (Map<String, Object>) entry.getValue());
    }
    return Collections.unmodifiableMap(dataMap);
}
Example 31
Project: Broadleaf-eCommerce-master  File: ResourceMinificationServiceImpl.java View source code
@Override
public byte[] minify(String filename, byte[] bytes) {
    if (!getEnabled()) {
        LOG.trace("Minification is disabled, returning original resource");
        return bytes;
    }
    Resource modifiedResource = minify(new ByteArrayResource(bytes), filename);
    if (modifiedResource instanceof GeneratedResource) {
        return ((GeneratedResource) modifiedResource).getBytes();
    } else {
        return bytes;
    }
}
Example 32
Project: BroadleafCommerce-master  File: ResourceMinificationServiceImpl.java View source code
@Override
public byte[] minify(String filename, byte[] bytes) {
    if (!getEnabled()) {
        LOG.trace("Minification is disabled, returning original resource");
        return bytes;
    }
    Resource modifiedResource = minify(new ByteArrayResource(bytes), filename);
    if (modifiedResource instanceof GeneratedResource) {
        return ((GeneratedResource) modifiedResource).getBytes();
    } else {
        return bytes;
    }
}
Example 33
Project: carewebframework-core-master  File: PropertyAwareResource.java View source code
/**
     * Use the application context to resolve any embedded property values within the original
     * resource.
     */
@Override
public void setApplicationContext(ApplicationContext appContext) throws BeansException {
    try (InputStream is = originalResource.getInputStream()) {
        ConfigurableListableBeanFactory beanFactory = ((AbstractRefreshableApplicationContext) appContext).getBeanFactory();
        StringBuilder sb = new StringBuilder();
        Iterator<String> iter = IOUtils.lineIterator(is, "UTF-8");
        boolean transformed = false;
        while (iter.hasNext()) {
            String line = iter.next();
            if (line.contains("${")) {
                transformed = true;
                line = beanFactory.resolveEmbeddedValue(line);
            }
            sb.append(line);
        }
        transformedResource = !transformed ? originalResource : new ByteArrayResource(sb.toString().getBytes());
    } catch (IOException e) {
        throw MiscUtil.toUnchecked(e);
    }
}
Example 34
Project: commerce-master  File: ResourceMinificationServiceImpl.java View source code
@Override
public byte[] minify(String filename, byte[] bytes) {
    if (!getEnabled()) {
        LOG.trace("Minification is disabled, returning original resource");
        return bytes;
    }
    Resource modifiedResource = minify(new ByteArrayResource(bytes), filename);
    if (modifiedResource instanceof GeneratedResource) {
        return ((GeneratedResource) modifiedResource).getBytes();
    } else {
        return bytes;
    }
}
Example 35
Project: grails-core-master  File: GroovyPageUnitTestResourceLoader.java View source code
@Override
public Resource getResource(String location) {
    if (location.startsWith(WEB_INF_PREFIX)) {
        location = location.substring(WEB_INF_PREFIX.length());
    }
    if (groovyPages.containsKey(location)) {
        try {
            return new ByteArrayResource(groovyPages.get(location).getBytes("UTF-8"), location);
        } catch (UnsupportedEncodingException e) {
        }
    }
    if (basePath == null) {
        String basedir = BuildSettings.BASE_DIR.getAbsolutePath();
        basePath = basedir + File.separatorChar + GrailsResourceUtils.VIEWS_DIR_PATH;
    }
    String path = basePath + location;
    path = makeCanonical(path);
    return new FileSystemResource(path);
}
Example 36
Project: grails-master  File: GroovyPageUnitTestResourceLoader.java View source code
@Override
public Resource getResource(String location) {
    if (location.startsWith(WEB_INF_PREFIX)) {
        location = location.substring(WEB_INF_PREFIX.length());
    }
    if (groovyPages.containsKey(location)) {
        try {
            return new ByteArrayResource(groovyPages.get(location).getBytes("UTF-8"), location);
        } catch (UnsupportedEncodingException e) {
        }
    }
    if (basePath == null) {
        String basedir = BuildSettings.BASE_DIR.getAbsolutePath();
        basePath = basedir + File.separatorChar + GrailsResourceUtils.VIEWS_DIR_PATH;
    }
    String path = basePath + location;
    path = makeCanonical(path);
    return new FileSystemResource(path);
}
Example 37
Project: hdiv-archive-master  File: FreeMarkerConfigurerTests.java View source code
public void testFreemarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws IOException, TemplateException {
    FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
    fcfb.setTemplateLoaderPath("file:/mydir");
    Properties settings = new Properties();
    settings.setProperty("localized_lookup", "false");
    fcfb.setFreemarkerSettings(settings);
    fcfb.setResourceLoader(new ResourceLoader() {

        public Resource getResource(String location) {
            if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) {
                throw new IllegalArgumentException(location);
            }
            return new ByteArrayResource("test".getBytes(), "test");
        }

        public ClassLoader getClassLoader() {
            return getClass().getClassLoader();
        }
    });
    fcfb.afterPropertiesSet();
    assertTrue(fcfb.getObject() instanceof Configuration);
    Configuration fc = (Configuration) fcfb.getObject();
    Template ft = fc.getTemplate("test");
    assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}
Example 38
Project: JProtobuf-rpc-http-master  File: HttpRPCServerTest.java View source code
@Test
public void testSimpleRPC() {
    // google protobuf defined idl 
    String idl = "package pkg; " + "option java_package = \"com.baidu.bjf.remoting.protobuf.simplestring\";" + "option java_outer_classname = \"StringTypeClass\";" + "message StringMessage { required string msg = 1;}  ";
    ByteArrayResource resource = new ByteArrayResource(idl.getBytes());
    HttpRPCServer httpRPCServer = null;
    try {
        // 创建RPC Server  指定端�
        httpRPCServer = new HttpRPCServer(8080, 10);
        IDLServiceExporter idlServiceExporter = new IDLServiceExporter();
        idlServiceExporter.setInputIDL(resource);
        idlServiceExporter.setOutputIDL(resource);
        idlServiceExporter.setServiceName("SimpleTest");
        idlServiceExporter.setInvoker(new ServerInvoker() {

            @Override
            public void invoke(IDLProxyObject input, IDLProxyObject output) throws Exception {
                if (input != null) {
                    // if has request
                    Object msg = input.get("msg");
                    System.out.println("Get 'msg' from request value =" + msg);
                }
                if (output != null) {
                    // if need response result
                    output.put("msg", "new message");
                }
            }
        });
        idlServiceExporter.afterPropertiesSet();
        // 新增RPC�务
        HttpServerRequestHandler httpHandler = new HttpServerRequestHandler(idlServiceExporter);
        httpRPCServer.addRPCHandler(httpHandler);
        // �动 RPC Server
        // �动,RPC�务url地�为: http://localhost:8080/{serviceExporter.getServiceName}
        httpRPCServer.start();
        // 客户端访问
        IDLProxyFactoryBean idlProxyFactoryBean = new IDLProxyFactoryBean();
        idlProxyFactoryBean.setServiceUrl("http://localhost:8080/SimpleTest");
        idlProxyFactoryBean.setInputIDL(resource);
        idlProxyFactoryBean.setOutputIDL(resource);
        idlProxyFactoryBean.afterPropertiesSet();
        ClientInvoker<IDLProxyObject, IDLProxyObject> invoker = idlProxyFactoryBean.getObject();
        // send request
        IDLProxyObject input = invoker.getInput();
        if (input != null) {
            input.put("msg", "hello message.");
        }
        IDLProxyObject result = invoker.invoke(input);
        if (result != null) {
            Object msg = result.get("msg");
            Assert.assertEquals("new message", msg);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpRPCServer != null) {
            httpRPCServer.stop(0);
        }
    }
}
Example 39
Project: lemon-master  File: AutoDeployer.java View source code
@PostConstruct
public void init() {
    if (!enable) {
        return;
    }
    if ((deploymentResources == null) || (deploymentResources.length == 0)) {
        return;
    }
    TenantDTO tenantDto = tenantConnector.findByCode(defaultTenantCode);
    RepositoryService repositoryService = processEngine.getRepositoryService();
    for (Resource resource : deploymentResources) {
        String resourceName = null;
        if (resource instanceof ContextResource) {
            resourceName = ((ContextResource) resource).getPathWithinContext();
        } else if (resource instanceof ByteArrayResource) {
            resourceName = resource.getDescription();
        } else {
            try {
                resourceName = resource.getFile().getAbsolutePath();
            } catch (IOException ex) {
                logger.debug(ex.getMessage(), ex);
                resourceName = resource.getFilename();
            }
        }
        try {
            DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(resourceName);
            if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
                deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
            } else {
                deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
            }
            Deployment deployment = deploymentBuilder.tenantId(tenantDto.getId()).deploy();
            logger.info("auto deploy : {}", resourceName);
            for (ProcessDefinition processDefinition : repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list()) {
                this.syncProcessDefinition(processDefinition.getId());
            }
        } catch (IOException ex) {
            throw new ActivitiException("couldn't auto deploy resource '" + resource + "': " + ex.getMessage(), ex);
        }
    }
}
Example 40
Project: spring-batch-admin-master  File: JobConfigurationRequestLoaderTests.java View source code
@Test
public void testParentApplicationContext() throws Exception {
    StaticApplicationContext parent = new StaticApplicationContext();
    parent.refresh();
    loader.setApplicationContext(parent);
    Collection<JobInfo> jobNames = loader.loadJobs(new ByteArrayResource(JOB_XML.getBytes(), "http://localhost/jobs/configurations"));
    assertEquals("[job]", jobNames.toString());
}
Example 41
Project: spring-cloud-aws-master  File: MailSenderAwsTest.java View source code
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
    helper.addTo(MailSenderAwsTest.this.recipientAddress);
    helper.setFrom(MailSenderAwsTest.this.senderAddress);
    helper.addAttachment("test.txt", new ByteArrayResource("attachment content".getBytes("UTF-8")));
    helper.setSubject("test subject with attachment");
    helper.setText("mime body", false);
}
Example 42
Project: spring-cloud-config-master  File: VaultEnvironmentRepository.java View source code
@Override
public Environment findOne(String application, String profile, String label) {
    String state = request.getHeader(STATE_HEADER);
    String newState = this.watch.watch(state);
    String[] profiles = StringUtils.commaDelimitedListToStringArray(profile);
    List<String> scrubbedProfiles = scrubProfiles(profiles);
    List<String> keys = findKeys(application, scrubbedProfiles);
    Environment environment = new Environment(application, profiles, label, null, newState);
    for (String key : keys) {
        // read raw 'data' key from vault
        String data = read(key);
        if (data != null) {
            // data is in json format of which, yaml is a superset, so parse
            final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            yaml.setResources(new ByteArrayResource(data.getBytes()));
            Properties properties = yaml.getObject();
            if (!properties.isEmpty()) {
                environment.add(new PropertySource("vault:" + key, properties));
            }
        }
    }
    return environment;
}
Example 43
Project: spring-cloud-stream-modules-master  File: ScriptableTransformProcessor.java View source code
@Bean
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public MessageProcessor<?> transformer() {
    String language = this.properties.getLanguage();
    String script = this.properties.getScript();
    logger.info("Input script is '{}', language is '{}'", script, language);
    Resource scriptResource = new ByteArrayResource(decodeScript(script).getBytes()) {

        // TODO until INT-3976
        @Override
        public String getFilename() {
            // Only the groovy script processor enforces this requirement for a name
            return "StaticScript";
        }
    };
    return Scripts.script(scriptResource).lang(language).variableGenerator(this.scriptVariableGenerator).get();
}
Example 44
Project: spring-framework-2.5.x-master  File: VelocityConfigurerTests.java View source code
public Resource getResource(String location) {
    if (location.equals("file:/mydir") || location.equals("file:/mydir/test")) {
        return new ByteArrayResource("test".getBytes(), "test");
    }
    try {
        return new UrlResource(location);
    } catch (MalformedURLException ex) {
        throw new IllegalArgumentException(ex.toString());
    }
}
Example 45
Project: spring-hadoop-master  File: YarnClusterCreateCommand.java View source code
private static Properties getPropertiesFromRawYaml(String raw) {
    if (StringUtils.isEmpty(raw)) {
        return new Properties();
    }
    Resource resource = new ByteArrayResource(raw.getBytes());
    YamlPropertiesFactoryBean ypfb = new YamlPropertiesFactoryBean();
    ypfb.setResources(resource);
    ypfb.afterPropertiesSet();
    return ypfb.getObject();
}
Example 46
Project: spring-xd-master  File: SingleTableDatabaseInitializer.java View source code
private Resource substitutePlaceholdersForResource(Resource resource) {
    StringBuilder script = new StringBuilder();
    try {
        EncodedResource er = new EncodedResource(resource);
        LineNumberReader lnr = new LineNumberReader(er.getReader());
        String line = lnr.readLine();
        while (line != null) {
            if (tableName != null && line.contains(TABLE_PLACEHOLDER)) {
                logger.debug("Substituting '" + TABLE_PLACEHOLDER + "' with '" + tableName + "' in '" + line + "'");
                line = line.replace(TABLE_PLACEHOLDER, tableName);
            }
            if (line.contains(COLUMNS_PLACEHOLDER)) {
                logger.debug("Substituting '" + COLUMNS_PLACEHOLDER + "' with '" + columns + "' in '" + line + "'");
                line = line.replace(COLUMNS_PLACEHOLDER, columns);
            }
            script.append(line + "\n");
            line = lnr.readLine();
        }
        lnr.close();
        return new ByteArrayResource(script.toString().getBytes());
    } catch (IOException e) {
        throw new InvalidDataAccessResourceUsageException("Unable to read script " + resource, e);
    }
}
Example 47
Project: geode-master  File: ConvertUtils.java View source code
/**
   * Converts the 2-dimensional byte array of file data, which includes the name of the file as
   * bytes followed by the byte content of the file, for all files being transmitted by Gfsh to the
   * GemFire Manager.
   * <p/>
   * 
   * @param fileData a 2 dimensional byte array of files names and file content.
   * @return an array of Spring Resource objects encapsulating the details (name and content) of
   *         each file being transmitted by Gfsh to the GemFire Manager.
   * @see org.springframework.core.io.ByteArrayResource
   * @see org.springframework.core.io.Resource
   * @see org.apache.geode.management.internal.cli.CliUtil#bytesToData(byte[][])
   * @see org.apache.geode.management.internal.cli.CliUtil#bytesToNames(byte[][])
   */
public static Resource[] convert(final byte[][] fileData) {
    if (fileData != null) {
        final String[] fileNames = CliUtil.bytesToNames(fileData);
        final byte[][] fileContent = CliUtil.bytesToData(fileData);
        final List<Resource> resources = new ArrayList<Resource>(fileNames.length);
        for (int index = 0; index < fileNames.length; index++) {
            final String filename = fileNames[index];
            resources.add(new ByteArrayResource(fileContent[index], String.format("Contents of JAR file (%1$s).", filename)) {

                @Override
                public String getFilename() {
                    return filename;
                }
            });
        }
        return resources.toArray(new Resource[resources.size()]);
    }
    return new Resource[0];
}
Example 48
Project: balerocms-enterprise-master  File: EmailService.java View source code
/*
     * Send HTML mail with attachment.
     */
public void sendMailWithAttachment(final String recipientName, final String recipientEmail, final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType, final Locale locale) throws MessagingException {
    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, /* multipart */
    "UTF-8");
    message.setSubject("Example HTML email with attachment");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);
    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-withattachment.html", ctx);
    message.setText(htmlContent, true);
    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);
    // Send mail
    this.mailSender.send(mimeMessage);
}
Example 49
Project: btpka3.github.com-master  File: SimpleCaptchaController.java View source code
/**
     * 获�指定的验��图片。
     *
     * @param hash
     *            �显示的验��图片的HashCode
     * @return 验��图片数�
     * @throws IOException
     */
@RequestMapping(value = "/{hash}", method = { RequestMethod.GET })
@ResponseBody
public ResponseEntity<? extends Object> getCaptcha(@PathVariable(value = "hash") String hash) throws IOException {
    ValueWrapper valueWrapper = cacheManager.getCache(CACHE_NAME).get(hash);
    if (valueWrapper == null || valueWrapper.get() == null) {
        return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
    }
    Captcha captcha = (Captcha) valueWrapper.get();
    String captchaHash = Integer.toString(captcha.toString().hashCode());
    String fileName = captchaHash + ".jpg'";
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    headers.setPragma("no-cache");
    headers.setCacheControl("no-cache");
    headers.setExpires(0);
    headers.setContentType(MediaType.IMAGE_JPEG);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ImageOutputStream imgOut = new MemoryCacheImageOutputStream(byteOut);
    ImageIO.write(captcha.getImage(), "jpg", imgOut);
    return new ResponseEntity<Resource>(new ByteArrayResource(byteOut.toByteArray()), HttpStatus.OK);
}
Example 50
Project: cms-ce-master  File: AbstractSendMailService.java View source code
public final void sendMail(AbstractMailTemplate template) throws IOException, MessagingException {
    MessageSettings settings = new MessageSettings();
    setFromSettings(template, settings);
    settings.setBody(template.getBody());
    final MimeMessageHelper message = createMessage(settings, template.isHtml() || !template.getAttachments().isEmpty());
    message.setSubject(template.getSubject());
    final Map<String, InputStream> attachments = template.getAttachments();
    for (final Map.Entry<String, InputStream> attachment : attachments.entrySet()) {
        message.addAttachment(attachment.getKey(), new ByteArrayResource(IOUtils.toByteArray(attachment.getValue())));
    }
    if (template.isHtml()) {
        message.setText("[You need html supported mail client to read this email]", template.getBody());
    } else {
        message.setText(template.getBody());
    }
    if (template.getMailRecipients().size() == 0) {
        this.log.info("No recipients specified, mail not sent.");
    }
    for (MailRecipient recipient : template.getMailRecipients()) {
        if (recipient.getEmail() != null) {
            final MailRecipientType type = recipient.getType();
            switch(type) {
                case TO_RECIPIENT:
                    message.addTo(recipient.getEmail(), recipient.getName());
                    break;
                case BCC_RECIPIENT:
                    message.addBcc(recipient.getEmail(), recipient.getName());
                    break;
                case CC_RECIPIENT:
                    message.addCc(recipient.getEmail(), recipient.getName());
                    break;
                default:
                    throw new RuntimeException("Unknown recipient type: " + type);
            }
        }
    }
    sendMessage(message);
}
Example 51
Project: FiWare-Template-Handler-master  File: SpringProcessEngineConfiguration.java View source code
protected void autoDeployResources(ProcessEngine processEngine) {
    if (deploymentResources != null && deploymentResources.length > 0) {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentName);
        for (Resource resource : deploymentResources) {
            String resourceName = null;
            if (resource instanceof ContextResource) {
                resourceName = ((ContextResource) resource).getPathWithinContext();
            } else if (resource instanceof ByteArrayResource) {
                resourceName = resource.getDescription();
            } else {
                try {
                    resourceName = resource.getFile().getAbsolutePath();
                } catch (IOException e) {
                    resourceName = resource.getFilename();
                }
            }
            try {
                if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
                    deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
                } else {
                    deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
                }
            } catch (IOException e) {
                throw new ActivitiException("couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
            }
        }
        deploymentBuilder.deploy();
    }
}
Example 52
Project: javaconfig-ftw-master  File: SpringProcessEngineConfiguration.java View source code
protected void autoDeployResources(ProcessEngine processEngine) {
    if (deploymentResources != null && deploymentResources.length > 0) {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentName);
        for (Resource resource : deploymentResources) {
            String resourceName = null;
            if (resource instanceof ContextResource) {
                resourceName = ((ContextResource) resource).getPathWithinContext();
            } else if (resource instanceof ByteArrayResource) {
                resourceName = resource.getDescription();
            } else {
                try {
                    resourceName = resource.getFile().getAbsolutePath();
                } catch (IOException e) {
                    resourceName = resource.getFilename();
                }
            }
            try {
                if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
                    deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
                } else {
                    deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
                }
            } catch (IOException e) {
                throw new ActivitiException("couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
            }
        }
        deploymentBuilder.deploy();
    }
}
Example 53
Project: jenkow-plugin-master  File: SpringProcessEngineConfiguration.java View source code
protected void autoDeployResources(ProcessEngine processEngine) {
    if (deploymentResources != null && deploymentResources.length > 0) {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentName);
        for (Resource resource : deploymentResources) {
            String resourceName = null;
            if (resource instanceof ContextResource) {
                resourceName = ((ContextResource) resource).getPathWithinContext();
            } else if (resource instanceof ByteArrayResource) {
                resourceName = resource.getDescription();
            } else {
                try {
                    resourceName = resource.getFile().getAbsolutePath();
                } catch (IOException e) {
                    resourceName = resource.getFilename();
                }
            }
            try {
                if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
                    deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
                } else {
                    deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
                }
            } catch (IOException e) {
                throw new ActivitiException("couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
            }
        }
        deploymentBuilder.deploy();
    }
}
Example 54
Project: jetty-project-master  File: SpringConfigurationProcessor.java View source code
public void init(URL url, Node root, XmlConfiguration configuration) {
    try {
        _configuration = configuration;
        Resource resource = (url != null) ? new UrlResource(url) : new ByteArrayResource(("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\">" + root).getBytes("UTF-8"));
        _beanFactory = new XmlBeanFactory(resource) {

            @Override
            protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
                _configuration.initializeDefaults(bw.getWrappedInstance());
                super.applyPropertyValues(beanName, mbd, bw, pvs);
            }
        };
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 55
Project: jetty.project-master  File: SpringConfigurationProcessor.java View source code
@Override
public void init(URL url, XmlParser.Node config, XmlConfiguration configuration) {
    try {
        _configuration = configuration;
        Resource resource = url != null ? new UrlResource(url) : new ByteArrayResource(("" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\">" + config).getBytes(StandardCharsets.UTF_8));
        _beanFactory = new DefaultListableBeanFactory() {

            @Override
            protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
                _configuration.initializeDefaults(bw.getWrappedInstance());
                super.applyPropertyValues(beanName, mbd, bw, pvs);
            }
        };
        new XmlBeanDefinitionReader(_beanFactory).loadBeanDefinitions(resource);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 56
Project: ldp4j-master  File: ConfigurationSummary.java View source code
private ResourceSource getResourceSource(Resource resource) {
    ResourceSource source = null;
    if (resource instanceof ClassPathResource) {
        source = ResourceSource.CLASSPATH;
    } else if (resource instanceof UrlResource) {
        source = ResourceSource.REMOTE;
    } else if (resource instanceof FileSystemResource) {
        source = ResourceSource.FILE_SYSTEM;
    } else if (resource instanceof InputStreamResource) {
        source = ResourceSource.STREAM;
    } else if (resource instanceof ByteArrayResource) {
        source = ResourceSource.RAW;
    } else {
        String type = resource.getClass().toString();
        if (CLAZZ_NAME.equals(type)) {
            source = ResourceSource.OSGI_BUNDLE;
        } else {
            source = ResourceSource.UNKNOWN;
        }
    }
    return source;
}
Example 57
Project: OG-Platform-master  File: ComponentConfigIniLoaderTest.java View source code
public void test_loadValid() {
    ConfigProperties properties = new ConfigProperties();
    ComponentConfigIniLoader loader = new ComponentConfigIniLoader(LOGGER, properties);
    String text = "# comment" + NEWLINE + "[global]" + NEWLINE + "a = c" + NEWLINE + "b = d" + NEWLINE + "" + NEWLINE + "[block]" + NEWLINE + "m = p" + NEWLINE + "n = ${a}" + // property from [global]
    NEWLINE + "o = ${input}" + // property from injected properties
    NEWLINE;
    Resource resource = new ByteArrayResource(text.getBytes(Charsets.UTF_8), "Test");
    properties.put("input", "text");
    ComponentConfig test = new ComponentConfig();
    loader.load(resource, 0, test);
    assertEquals(2, test.getGroups().size());
    ConfigProperties testGlobal = test.getGroup("global");
    assertEquals(2, testGlobal.size());
    assertEquals("c", testGlobal.getValue("a"));
    assertEquals("d", testGlobal.getValue("b"));
    ConfigProperties testBlock = test.getGroup("block");
    assertEquals(3, testBlock.size());
    assertEquals("p", testBlock.getValue("m"));
    assertEquals("c", testBlock.getValue("n"));
    assertEquals("text", testBlock.getValue("o"));
}
Example 58
Project: OpenConext-api-master  File: GroupServiceBasicAuthentication10aTest.java View source code
@Test
public void testGetGroupMembersEntryFaultyHttpResponse() {
    super.setResponseResource(new ByteArrayResource("not-even-valid-json".getBytes()));
    super.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    GroupMembersEntry groupMembersEntry = groupService.getGroupMembersEntry(provider, "personId", "whatever", 0, 0);
    assertTrue(groupMembersEntry.getEntry().isEmpty());
}
Example 59
Project: phantom-master  File: HandlerConfigController.java View source code
@RequestMapping(value = { "/deploy/**" }, method = RequestMethod.POST)
public String deployModifiedConfig(ModelMap model, HttpServletRequest request, @ModelAttribute("handlerName") String handlerName, @RequestParam(defaultValue = "") String XMLFileContents, @RequestParam(defaultValue = "0") String identifier) {
    //Save the file
    XMLFileContents = XMLFileContents.trim();
    if (identifier.equals("Save")) {
        try {
            this.configService.modifyHandlerConfig(handlerName, new ByteArrayResource(XMLFileContents.getBytes()));
        } catch (//Loading failed
        Exception //Loading failed
        e) {
            model.addAttribute("XMLFileError", "Unable to deploy file");
            StringWriter errors = new StringWriter();
            e.printStackTrace(new PrintWriter(errors));
            model.addAttribute("LoadingError", errors.toString());
            if (errors.toString() == null) {
                model.addAttribute("LoadingError", "Unexpected error");
            }
            model.addAttribute("XMLFileContents", ConfigFileUtils.getContents(this.configService.getHandlerConfig(handlerName)));
            return "modifyConfig";
        }
    }
    //Loading success
    model.addAttribute("SuccessMessage", "Successfully Deployed the new Handler Configuration");
    model.addAttribute("taskHandlers", this.configService.getAllHandlers());
    Resource handlerFile = this.configService.getHandlerConfig(handlerName);
    model.addAttribute("XMLFileContents", ConfigFileUtils.getContents(handlerFile));
    try {
        model.addAttribute("XMLFileName", handlerFile.getURI());
    } catch (IOException e) {
        model.addAttribute("XMLFileName", "File not found");
    }
    return "viewConfig";
}
Example 60
Project: qcadoo-master  File: ModelXmlResolverImpl.java View source code
@Override
public Resource[] getResources() {
    List<Resource> resources = new ArrayList<Resource>();
    addFields();
    addHooks();
    for (Document document : documents.values()) {
        byte[] out = JdomUtils.documentToByteArray(document);
        if (LOG.isDebugEnabled()) {
            LOG.debug(new String(out));
        }
        resources.add(new ByteArrayResource(out));
    }
    documents.clear();
    fields.clear();
    hooks.clear();
    return resources.toArray(new Resource[resources.size()]);
}
Example 61
Project: spring-cloud-consul-master  File: ConsulPropertySource.java View source code
protected Properties generateProperties(String value, ConsulConfigProperties.Format format) {
    final Properties props = new Properties();
    if (format == PROPERTIES) {
        try {
            // Must use the ISO-8859-1 encoding because Properties.load(stream)
            // expects it.
            props.load(new ByteArrayInputStream(value.getBytes("ISO-8859-1")));
        } catch (IOException e) {
            throw new IllegalArgumentException(value + " can't be encoded using ISO-8859-1");
        }
        return props;
    } else if (format == YAML) {
        final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ByteArrayResource(value.getBytes()));
        return yaml.getObject();
    }
    return props;
}
Example 62
Project: spring-js-master  File: ResourceScriptSourceTests.java View source code
public void testLastModifiedWorksWithResourceThatDoesNotSupportFileBasedAccessAtAll() throws Exception {
    Resource resource = new ByteArrayResource(new byte[0]);
    ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
    assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified());
    scriptSource.getScriptAsString();
    assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified());
    // Must now continue to report back as not having been modified 'cos the Resource does not support access as a File (and so the lastModified date cannot be determined).
    assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified());
}
Example 63
Project: aesop-master  File: RuntimeConfigServiceImpl.java View source code
/**
	 * Interface method implementation.
	 * @see com.flipkart.aesop.runtime.spi.admin.RuntimeConfigService#modifyRuntimeConfig(java.lang.String, org.springframework.core.io.ByteArrayResource)
	 */
public void modifyRuntimeConfig(String runtimeName, ByteArrayResource modifiedRuntimeConfigFile) throws PlatformException {
    // Check if exists
    File oldRuntimeFile = null;
    try {
        oldRuntimeFile = this.getRuntimeConfig(runtimeName).getFile();
    } catch (IOException e1) {
        LOGGER.error("Config File for runtime: " + runtimeName + " not found. Returning");
        throw new PlatformException("File not found for runtime: " + runtimeName, e1);
    }
    if (!oldRuntimeFile.exists()) {
        LOGGER.error("Runtime Config File: " + oldRuntimeFile.getAbsolutePath() + " doesn't exist. Returning");
        throw new PlatformException("File not found: " + oldRuntimeFile.getAbsolutePath());
    }
    // Check for read permissions
    if (!oldRuntimeFile.canRead()) {
        LOGGER.error("No read permission for: " + oldRuntimeFile.getAbsolutePath() + ". Returning");
        throw new PlatformException("Read permissions not found for file: " + oldRuntimeFile.getAbsolutePath());
    }
    // Check for write permissions
    if (!oldRuntimeFile.canWrite()) {
        LOGGER.error("No write permission for: " + oldRuntimeFile.getAbsolutePath() + ". Write permissions are required to modify runtime config");
        throw new PlatformException("Required permissions not found for modifying file: " + oldRuntimeFile.getAbsolutePath());
    }
    // create backup
    this.createPrevConfigFile(runtimeName);
    // file_put_contents Java :-/
    try {
        this.upload(modifiedRuntimeConfigFile.getByteArray(), oldRuntimeFile.getAbsolutePath());
    } catch (IOException e) {
        LOGGER.error("IOException while uploading file to path: " + oldRuntimeFile.getAbsolutePath());
        this.restorePrevConfigFile(runtimeName);
        throw new PlatformException(e);
    }
    // get the registered ServerContainer for the file name
    ServerContainer runtime = this.configURItoRuntimeName.get(oldRuntimeFile.toURI()).get(0);
    // this mean this only works if only one runtime per runtime xml file
    try {
        this.componentContainer.reloadRuntime(runtime, this.getRuntimeConfig(runtimeName));
    } catch (Exception e) {
        this.restorePrevConfigFile(runtimeName);
        this.componentContainer.loadComponent(this.getRuntimeConfig(runtimeName));
        throw new PlatformException(e);
    }
    this.removePrevConfigFile(runtimeName);
}
Example 64
Project: anudc-master  File: ReportRunnable.java View source code
@Override
public void run() {
    Date date = new Date();
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    LOGGER.info("Report {} sends to {} with parameters:", reportAuto.getReportId(), reportAuto.getEmail());
    if (reportAuto.getReportAutoParams() != null) {
        for (ReportAutoParam param : reportAuto.getReportAutoParams()) {
            LOGGER.info("Parameter {} with value {}", param.getParam(), param.getParamVal());
        }
    }
    String path = context.getRealPath("/");
    ReportGenerator reportGenerator = new ReportGenerator(reportAuto, path);
    try {
        byte[] bytes = reportGenerator.generateReportForEmail(reportAuto.getFormat());
        //byte[] bytes = reportGenerator.generateReportPDF();
        ByteArrayResource byteArrayResource = new ByteArrayResource(bytes);
        if (Boolean.parseBoolean(GlobalProps.getProperty(GlobalProps.PROP_EMAIL_DEBUG_SEND, "false"))) {
            MimeMessage message = mailSender.createMimeMessage();
            try {
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom("no-reply@anu.edu.au", "ANU Data Commons");
                helper.setTo(reportAuto.getEmail());
                helper.setSubject(emailSubject);
                String body = getBody();
                helper.setText(getBody());
                String filename = "report-" + sdf2.format(date) + getExtension(reportAuto.getFormat());
                helper.addAttachment(filename, byteArrayResource);
                LOGGER.info("Sending email...\r\nTO: {}\r\nSUBJECT: {}\r\nBODY: {}\r\nATTACHMENT: {}", new Object[] { reportAuto.getEmail(), emailSubject, body, filename });
                mailSender.send(message);
            } catch (MessagingExceptionIOException |  e) {
                LOGGER.error("Exception generating or sending email", e);
            }
        } else {
            LOGGER.debug("Report has been generated, not sending due to emails being set to false");
        }
    } catch (JRExceptionSQLException | IOException | ClassNotFoundException |  e) {
        LOGGER.error("Error generating pdf", e);
    }
}
Example 65
Project: cas-master  File: CRLDistributionPointRevocationChecker.java View source code
@Override
protected List<X509CRL> getCRLs(final X509Certificate cert) {
    if (this.crlCache == null) {
        throw new IllegalArgumentException("CRL cache is not defined");
    }
    if (this.fetcher == null) {
        throw new IllegalArgumentException("CRL fetcher is not defined");
    }
    if (getExpiredCRLPolicy() == null) {
        throw new IllegalArgumentException("Expiration CRL policy is not defined");
    }
    if (getUnavailableCRLPolicy() == null) {
        throw new IllegalArgumentException("Unavailable CRL policy is not defined");
    }
    final URI[] urls = getDistributionPoints(cert);
    LOGGER.debug("Distribution points for [{}]: [{}].", CertUtils.toString(cert), Arrays.asList(urls));
    final List<X509CRL> listOfLocations = new ArrayList<>(urls.length);
    boolean stopFetching = false;
    try {
        for (int index = 0; !stopFetching && index < urls.length; index++) {
            final URI url = urls[index];
            final Element item = this.crlCache.get(url);
            if (item != null) {
                LOGGER.debug("Found CRL in cache for [{}]", CertUtils.toString(cert));
                final byte[] encodedCrl = (byte[]) item.getObjectValue();
                final X509CRL crlFetched = this.fetcher.fetch(new ByteArrayResource(encodedCrl));
                if (crlFetched != null) {
                    listOfLocations.add(crlFetched);
                } else {
                    LOGGER.warn("Could fetch X509 CRL for [{}]. Returned value is null", url);
                }
            } else {
                LOGGER.debug("CRL for [{}] is not cached. Fetching and caching...", CertUtils.toString(cert));
                try {
                    final X509CRL crl = this.fetcher.fetch(url);
                    if (crl != null) {
                        LOGGER.info("Success. Caching fetched CRL at [{}].", url);
                        addCRL(url, crl);
                        listOfLocations.add(crl);
                    }
                } catch (final Exception e) {
                    LOGGER.error("Error fetching CRL at [{}]", url, e);
                    if (this.throwOnFetchFailure) {
                        throw Throwables.propagate(e);
                    }
                }
            }
            if (!this.checkAll && !listOfLocations.isEmpty()) {
                LOGGER.debug("CRL fetching is configured to not check all locations.");
                stopFetching = true;
            }
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
    LOGGER.debug("Found [{}] CRLs", listOfLocations.size());
    return listOfLocations;
}
Example 66
Project: manager.v3-master  File: InstanceInfoTest.java View source code
/**
   * Shows that getBytes() is harmless with properties files, which
   * are encoded using ASCII anyway.
   */
public void testNonAsciiProperties() throws Exception {
    String expected = "foncé";
    ByteArrayResource resource = (ByteArrayResource) InstanceInfo.getPropertiesResource("fred", ImmutableMap.of("Color", expected));
    String props = new String(resource.getByteArray());
    assertFalse(props, props.contains(expected));
    Properties properties = PropertiesUtils.loadFromString(props);
    assertEquals(expected, properties.getProperty("Color"));
}
Example 67
Project: MLDS-master  File: ReleasePackagesResource.java View source code
private ResponseEntity<?> downloadFile(HttpServletRequest request, File file) throws SQLException, IOException {
    if (file == null) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } else if (file.getLastUpdated() != null) {
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        long lastUpdatedSecondsFloor = file.getLastUpdated().getMillis() / 1000 * 1000;
        if (ifModifiedSince != -1 && lastUpdatedSecondsFloor <= ifModifiedSince) {
            return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
        }
    }
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.valueOf(file.getMimetype()));
    httpHeaders.setContentLength(file.getContent().length());
    httpHeaders.setContentDispositionFormData("file", file.getFilename());
    if (file.getLastUpdated() != null) {
        httpHeaders.setLastModified(file.getLastUpdated().getMillis());
    }
    byte[] byteArray = IOUtils.toByteArray(file.getContent().getBinaryStream());
    org.springframework.core.io.Resource contents = new ByteArrayResource(byteArray);
    return new ResponseEntity<org.springframework.core.io.Resource>(contents, httpHeaders, HttpStatus.OK);
}
Example 68
Project: sched-assist-master  File: AdvisorListRelationshipDataSourceImplTest.java View source code
/**
	 * Test readResource function with {@link ByteArrayResource}/
	 * 
	 * @throws Exception
	 */
@Test
public void testReadResource() throws Exception {
    String example1 = "student1@wisc.edu;One,Test Student;0000000001;9010000001;Graduate;L&S;College of Letters and Science;4.000;1092;Fall 2008-2009;87.000;PHD 922L&S;;NWD;G922L;Sociology - LS;PHD 922L&S;Sociology PHD-L&S;Sociology;advisor1@wisc.edu;One,Advisor;1000000001;9020000001;ADVR;Academic";
    String example2 = "student2@wisc.edu;Two,Test Student;0000000002;9010000002;Senior;NUR;School of Nursing;3.556;1094;Spring 2008-2009;128.000;NUR 712;;NWD;NUR;Nursing Undergraduate;NUR 712;Nursing NUR;Nursing;advisor2@wisc.edu;Two,Advisor;1000000002;9020000002;ADVR;Academic";
    StringBuilder builder = new StringBuilder();
    builder.append(example1);
    builder.append("\n");
    builder.append(example2);
    ByteArrayResource sampleResource = new ByteArrayResource(builder.toString().getBytes());
    AdvisorListRelationshipDataSourceImpl dataSource = new AdvisorListRelationshipDataSourceImpl();
    List<StudentAdvisorAssignment> records = dataSource.readResource(sampleResource, "1094");
    Assert.assertEquals(1, records.size());
    StudentAdvisorAssignment record = records.get(0);
    Assert.assertEquals("1000000002", record.getAdvisorEmplid());
    Assert.assertEquals("Nursing Undergraduate", record.getAdvisorRelationshipDescription());
    Assert.assertEquals("0000000002", record.getStudentEmplid());
    Assert.assertEquals("1094", record.getTermNumber());
    Assert.assertEquals("Spring 2008-2009", record.getTermDescription());
    Assert.assertEquals("Academic", record.getAdvisorType());
    records = dataSource.readResource(sampleResource, "1092");
    Assert.assertEquals(2, records.size());
}
Example 69
Project: spacesimulator-master  File: ModelController.java View source code
@RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
public ResponseEntity<ByteArrayResource> download(@PathVariable("id") String id) throws IOException {
    logger.info("get id = {}", id);
    ModelRunnable runnable = modelExecutor.get(id);
    Model m = getModelSnapshot(id, runnable);
    byte[] bytes = modelSerializer.toBytes(m);
    ByteArrayResource resource = new ByteArrayResource(bytes);
    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType(new MediaType("application", "json"));
    respHeaders.setContentLength(resource.contentLength());
    respHeaders.setContentDispositionFormData("attachment", m.getName() + ".json");
    ResponseEntity<ByteArrayResource> result = new ResponseEntity<ByteArrayResource>(resource, respHeaders, HttpStatus.OK);
    return result;
}
Example 70
Project: spring-integration-samples-master  File: MimeMessageParsingTest.java View source code
/**
	 * This test will create a Mime Message that contains an Attachment, send it
	 * to an SMTP Server (Using Wiser) and retrieve and process the Mime Message.
	 *
	 * This test verifies that the parsing of the retrieved Mime Message is
	 * successful and that the correct number of {@link EmailFragment}s is created.
	 */
@Test
public void testProcessingOfEmailAttachments() {
    final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setPort(this.wiserPort);
    final MimeMessage message = mailSender.createMimeMessage();
    final String pictureName = "picture.png";
    final ByteArrayResource byteArrayResource = getFileData(pictureName);
    try {
        final MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("testfrom@springintegration.org");
        helper.setTo("testto@springintegration.org");
        helper.setSubject("Parsing of Attachments");
        helper.setText("Spring Integration Rocks!");
        helper.addAttachment(pictureName, byteArrayResource, "image/png");
    } catch (MessagingException e) {
        throw new MailParseException(e);
    }
    mailSender.send(message);
    final List<WiserMessage> wiserMessages = wiser.getMessages();
    Assert.assertTrue(wiserMessages.size() == 1);
    boolean foundTextMessage = false;
    boolean foundPicture = false;
    for (WiserMessage wiserMessage : wiserMessages) {
        final List<EmailFragment> emailFragments = new ArrayList<EmailFragment>();
        try {
            final MimeMessage mailMessage = wiserMessage.getMimeMessage();
            EmailParserUtils.handleMessage(null, mailMessage, emailFragments);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving Mime Message.");
        }
        Assert.assertTrue(emailFragments.size() == 2);
        for (EmailFragment emailFragment : emailFragments) {
            if ("picture.png".equals(emailFragment.getFilename())) {
                foundPicture = true;
            }
            if ("message.txt".equals(emailFragment.getFilename())) {
                foundTextMessage = true;
            }
        }
        Assert.assertTrue(foundPicture);
        Assert.assertTrue(foundTextMessage);
    }
}
Example 71
Project: spring-ws-master  File: MockWebServiceServerTest.java View source code
@Test
public void xsdMatch() throws Exception {
    Resource schema = new ByteArrayResource("<schema xmlns=\"http://www.w3.org/2001/XMLSchema\" targetNamespace=\"http://example.com\" elementFormDefault=\"qualified\"><element name=\"request\"/></schema>".getBytes());
    server.expect(validPayload(schema));
    StringResult result = new StringResult();
    String actual = "<request xmlns='http://example.com'/>";
    template.sendSourceAndReceiveToResult(new StringSource(actual), result);
}
Example 72
Project: gemini.blueprint-master  File: JarCreator.java View source code
/**
	 * Resolve the jar content based on its path. Will return a map containing
	 * the entries relative to the jar root path as keys and Spring Resource
	 * pointing to the actual resources as values. It will also determine the
	 * packages contained by this package.
	 * 
	 * @return
	 */
public Map resolveContent() {
    Resource[][] resources = resolveResources();
    URL rootURL;
    String rootP = getRootPath();
    try {
        rootURL = new URL(rootP);
    } catch (MalformedURLException ex) {
        throw (RuntimeException) new IllegalArgumentException("illegal root path given " + rootP).initCause(ex);
    }
    String rootPath = StringUtils.cleanPath(rootURL.getPath());
    // remove duplicates
    Map entries = new TreeMap();
    // save contained bundle packages
    containedPackages.clear();
    // empty stream used for folders
    Resource folderResource = new ByteArrayResource(new byte[0]);
    // add folder entries also
    for (int i = 0; i < resources.length; i++) {
        for (int j = 0; j < resources[i].length; j++) {
            String relativeName = determineRelativeName(rootPath, resources[i][j]);
            // be consistent when adding resources to jar
            if (!relativeName.startsWith("/"))
                relativeName = "/" + relativeName;
            entries.put(relativeName, resources[i][j]);
            // look for class entries
            if (relativeName.endsWith(CLASS_EXT)) {
                // determine package (exclude first char)
                String clazzName = relativeName.substring(1, relativeName.length() - CLASS_EXT.length()).replace('/', '.');
                // remove class name
                int index = clazzName.lastIndexOf('.');
                if (index > 0)
                    clazzName = clazzName.substring(0, index);
                // add it to the collection
                containedPackages.add(clazzName);
            }
            String token = relativeName;
            // get folder and walk up to the root
            if (addFolders) {
                // add META-INF
                entries.put("/META-INF/", folderResource);
                int slashIndex;
                // stop at root folder
                while ((slashIndex = token.lastIndexOf('/')) > 1) {
                    // add the folder with trailing /
                    entries.put(token.substring(0, slashIndex + 1), folderResource);
                    // walk the tree
                    token = token.substring(0, slashIndex);
                }
            // add root folder
            //entries.put("/", folderResource);
            }
        }
    }
    if (log.isTraceEnabled())
        log.trace("The following packages were discovered in the bundle: " + containedPackages);
    return entries;
}
Example 73
Project: HotswapAgent-master  File: ClassPathBeanDefinitionScannerAgent.java View source code
/**
     * Resolve bean definition from class definition if applicable.
     *
     * @param bytes class definition.
     * @return the definition or null if not a spring bean
     * @throws IOException
     */
public BeanDefinition resolveBeanDefinition(byte[] bytes) throws IOException {
    Resource resource = new ByteArrayResource(bytes);
    resetCachingMetadataReaderFactoryCache();
    MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
    if (isCandidateComponent(metadataReader)) {
        ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
        sbd.setResource(resource);
        sbd.setSource(resource);
        if (isCandidateComponent(sbd)) {
            LOGGER.debug("Identified candidate component class '{}'", metadataReader.getClassMetadata().getClassName());
            return sbd;
        } else {
            LOGGER.debug("Ignored because not a concrete top-level class '{}'", metadataReader.getClassMetadata().getClassName());
            return null;
        }
    } else {
        LOGGER.trace("Ignored because not matching any filter '{}' ", metadataReader.getClassMetadata().getClassName());
        return null;
    }
}
Example 74
Project: login-server-master  File: IdentityProviderConfiguratorTests.java View source code
private void parseYaml(String sampleYaml) {
    YamlMapFactoryBean factory = new YamlMapFactoryBean();
    factory.setResolutionMethod(YamlProcessor.ResolutionMethod.OVERRIDE_AND_IGNORE);
    List<Resource> resources = new ArrayList<>();
    ByteArrayResource resource = new ByteArrayResource(sampleYaml.getBytes());
    resources.add(resource);
    factory.setResources(resources.toArray(new Resource[resources.size()]));
    Map<String, Object> tmpdata = factory.getObject();
    data = new HashMap<>();
    for (Map.Entry<String, Object> entry : ((Map<String, Object>) tmpdata.get("providers")).entrySet()) {
        data.put(entry.getKey(), (Map<String, Object>) entry.getValue());
    }
}
Example 75
Project: spring-cloud-dataflow-master  File: AppRegistryController.java View source code
/**
	 * Register all applications listed in a properties file or provided as key/value
	 * pairs.
	 *
	 * @param pagedResourcesAssembler the resource asembly for app registrations
	 * @param uri URI for the properties file
	 * @param apps key/value pairs representing applications, separated by newlines
	 * @param force if {@code true}, overwrites any pre-existing registrations
	 * @return the collection of registered applications
	 * @throws IOException if can't store the Properties object to byte output stream
	 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public PagedResources<? extends AppRegistrationResource> registerAll(PagedResourcesAssembler<AppRegistration> pagedResourcesAssembler, @RequestParam(value = "uri", required = false) String uri, @RequestParam(value = "apps", required = false) Properties apps, @RequestParam(value = "force", defaultValue = "false") boolean force) throws IOException {
    List<AppRegistration> registrations = new ArrayList<>();
    if (StringUtils.hasText(uri)) {
        registrations.addAll(appRegistry.importAll(force, resourceLoader.getResource(uri)));
    } else if (!CollectionUtils.isEmpty(apps)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        apps.store(baos, "");
        ByteArrayResource bar = new ByteArrayResource(baos.toByteArray(), "Inline properties");
        registrations.addAll(appRegistry.importAll(force, bar));
    }
    Collections.sort(registrations);
    prefetchMetadata(registrations);
    return pagedResourcesAssembler.toResource(new PageImpl<>(registrations), assembler);
}
Example 76
Project: BlackboardVCPortlet-master  File: MailTemplateServiceImpl.java View source code
public void prepare(MimeMessage mimeMessage) throws Exception {
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
    if (mt.getMeetingInvite() != null) {
        CalendarOutputter outputter = new CalendarOutputter();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        outputter.setValidating(false);
        outputter.output(mt.getMeetingInvite(), os);
        message.addAttachment("invite.ics", new ByteArrayResource(os.toByteArray()));
    }
    message.setFrom(mt.getFrom() != null ? mt.getFrom() : defaultFromAddress);
    if (mt.getTo() != null) {
        String[] toArray = mt.getTo().toArray(new String[mt.getTo().size()]);
        message.setTo(toArray);
    }
    if (mt.getSubject() != null) {
        message.setSubject(mt.getSubject());
    } else {
        switch(mt.getTemplate()) {
            case MODERATOR:
                message.setSubject(moderatorSubject);
                break;
            case INTERNAL_PARTICIPANT:
                message.setSubject(internalParticipantSubject);
                break;
            case EXTERNAL_PARTICIPANT:
                message.setSubject(externalParticipantSubject);
                break;
            case SESSION_DELETION:
                message.setSubject(sessionDeletionSubject);
                break;
            default:
                message.setSubject("");
        }
    }
    message.setText(buildEmailMessage(mt), false);
}
Example 77
Project: citrus-master  File: SchemaBaseTests.java View source code
@Before
public void init() throws Exception {
    source = new ByteArrayResource("<hello></hello>".getBytes());
    illegalSource = new ByteArrayResource("<hello>".getBytes());
    transformer = new Transformer() {

        public void transform(Document document, String systemId) {
            document.getRootElement().addElement("world");
        }
    };
    transformer2 = new Transformer() {

        public void transform(Document document, String systemId) {
            document.getRootElement().addElement("hi");
        }
    };
    document = SchemaUtil.readDocument(new ByteArrayInputStream("<doc></doc>".getBytes()), "", true);
    schema = new SchemaBaseImpl(source);
}
Example 78
Project: MULE-master  File: MuleArtifactContext.java View source code
private static Resource[] convert(ConfigResource[] resources) {
    Resource[] configResources = new Resource[resources.length];
    for (int i = 0; i < resources.length; i++) {
        ConfigResource resource = resources[i];
        if (resource.getUrl() != null) {
            configResources[i] = new UrlResource(resource.getUrl());
        } else {
            try {
                configResources[i] = new ByteArrayResource(IOUtils.toByteArray(resource.getInputStream()), resource.getResourceName());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return configResources;
}
Example 79
Project: spring-social-slideshare-master  File: SlideshowTemplate.java View source code
@Override
public String uploadSlideshowFromContent(String username, String password, byte[] slideshowContent, final String filename, String title, String description, Collection<String> tags, boolean makeSrcPublic, Boolean makeSlideshowPrivate, Boolean generateSecretUrl, Boolean allowEmbeds, Boolean shareWithContacts) {
    Resource resource = new ByteArrayResource(slideshowContent) {

        @Override
        public String getFilename() {
            // SS API requires to provide filename
            return filename;
        }
    };
    return uploadSlideshowResource(username, password, resource, title, description, tags, makeSrcPublic, makeSlideshowPrivate, generateSecretUrl, allowEmbeds, shareWithContacts);
}
Example 80
Project: wooki-master  File: ConversionsTest.java View source code
@Test(enabled = true)
public void testAPTConversion() {
    String result = /*
                         * generator .adaptContent(
                         */
    "<h2>SubTitle</h2><p>Lorem ipsum</p><h3>SubTitle2</h3><p>Lorem ipsum</p>";
    Resource resource = new ByteArrayResource(result.getBytes());
    InputStream xhtml = toXHTMLConvertor.performTransformation(resource);
    logger.debug("Document to xhtml ok");
    InputStream apt = toAPTConvertor.performTransformation(new InputStreamResource(xhtml));
    logger.debug("xhtml to apt ok");
    File aptFile;
    try {
        aptFile = File.createTempFile("wooki", ".apt");
        FileOutputStream fos = new FileOutputStream(aptFile);
        logger.debug("APT File is " + aptFile.getAbsolutePath());
        byte[] content = null;
        int available = 0;
        while ((available = apt.available()) > 0) {
            content = new byte[available];
            apt.read(content);
            fos.write(content);
        }
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 81
Project: solarnetwork-node-master  File: CASettingsService.java View source code
@Override
public Iterable<BackupResource> getBackupResources() {
    // create resource from our settings CSV data
    ByteArrayOutputStream byos = new ByteArrayOutputStream();
    try {
        OutputStreamWriter writer = new OutputStreamWriter(byos, "UTF-8");
        exportSettingsCSV(writer);
    } catch (IOException e) {
        log.error("Unable to create settings backup resource", e);
    }
    List<BackupResource> resources = new ArrayList<BackupResource>(1);
    resources.add(new ResourceBackupResource(new ByteArrayResource(byos.toByteArray()), BACKUP_RESOURCE_SETTINGS_CSV, getKey()));
    return resources;
}
Example 82
Project: OpenSpaces-master  File: PUServiceBeanImpl.java View source code
private void startPU(String springXml) throws IOException, ClassNotFoundException {
    if (logger.isDebugEnabled()) {
        logger.debug(logMessage("Starting PU with [" + springXml + "]"));
    }
    String puName = (String) context.getInitParameter("puName");
    String puPath = (String) context.getInitParameter("puPath");
    String codeserver = context.getExportCodebase();
    org.openspaces.pu.sla.SLA sla = getSLA(getServiceBeanContext());
    Integer instanceId = this.instanceId;
    Integer backupId = this.backupId;
    // Derive instanceId and backupId if not explicitly set
    if (instanceId == null) {
        boolean hasBackups = sla.getNumberOfBackups() > 0;
        if (hasBackups) {
            instanceId = clusterGroup;
            //the first instance is primary so no backupid
            if (context.getServiceBeanConfig().getInstanceID().intValue() > 1) {
                backupId = (context.getServiceBeanConfig().getInstanceID().intValue() - 1);
            }
        } else {
            instanceId = context.getServiceBeanConfig().getInstanceID().intValue();
        }
    }
    //set cluster info
    clusterInfo = new ClusterInfo();
    String clusterSchema = sla.getClusterSchema();
    if (clusterSchema != null) {
        clusterInfo.setSchema(clusterSchema);
        int slaMax = getSLAMax(context);
        int numberOfInstances = Math.max(slaMax, sla.getNumberOfInstances());
        clusterInfo.setNumberOfInstances(numberOfInstances);
    } else {
        clusterInfo.setNumberOfInstances(sla.getNumberOfInstances());
    }
    clusterInfo.setNumberOfBackups(sla.getNumberOfBackups());
    clusterInfo.setInstanceId(instanceId);
    clusterInfo.setBackupId(backupId);
    clusterInfo.setName(puName);
    ClusterInfoParser.guessSchema(clusterInfo);
    logger.info(logMessage("ClusterInfo [" + clusterInfo + "]"));
    MarshalledObject beanLevelPropertiesMarshObj = (MarshalledObject) getServiceBeanContext().getInitParameter("beanLevelProperties");
    BeanLevelProperties beanLevelProperties;
    if (beanLevelPropertiesMarshObj != null) {
        beanLevelProperties = (BeanLevelProperties) beanLevelPropertiesMarshObj.get();
        logger.info(logMessage("BeanLevelProperties " + beanLevelProperties));
    } else {
        beanLevelProperties = new BeanLevelProperties();
    }
    beanLevelProperties.getContextProperties().putAll(ClusterInfoPropertyPlaceholderConfigurer.createProperties(clusterInfo));
    // set a generic work location that can be used by container providers
    File workLocation = new File(System.getProperty("com.gs.work", Environment.getHomeDirectory() + "/work"));
    workLocation.mkdirs();
    beanLevelProperties.getContextProperties().setProperty("com.gs.work", workLocation.getAbsolutePath());
    boolean downloadPU = false;
    //create PU Container
    ProcessingUnitContainerProvider factory;
    // identify if this is a web app
    InputStream webXml = null;
    try {
        webXml = new URL(codeserver + puPath + "/WEB-INF/web.xml").openStream();
    } catch (IOException e) {
    }
    // identify if this is a .NET one
    InputStream puConfig = null;
    try {
        puConfig = new URL(codeserver + puPath + "/pu.config").openStream();
    } catch (IOException e) {
    }
    // identify if this is a .NET interop one
    InputStream puInteropConfig = null;
    try {
        puInteropConfig = new URL(codeserver + puPath + "/pu.interop.config").openStream();
    } catch (IOException e) {
    }
    String processingUnitContainerProviderClass;
    if (webXml != null) {
        webXml.close();
        downloadPU = true;
        String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties);
        String[] classesToLoad = null;
        if ("jetty".equals(jeeContainer)) {
            // pre load the jetty server class so the static shutdown thread will be loaded under it
            classesToLoad = new String[] { "org.eclipse.jetty.server.Server" };
        }
        // setup class loaders correcly
        try {
            Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance());
            ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer) }));
            ((ServiceClassLoader) contextClassLoader).setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad));
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to configure JEE class loader", e);
        } finally {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
        String className = StringUtils.capitalize(jeeContainer) + "JeeProcessingUnitContainerProvider";
        processingUnitContainerProviderClass = "org.openspaces.pu.container.jee." + jeeContainer + "." + className;
    } else if (puConfig != null) {
        puConfig.close();
        downloadPU = true;
        processingUnitContainerProviderClass = DotnetProcessingUnitContainerProvider.class.getName();
    } else if (puInteropConfig != null) {
        puInteropConfig.close();
        downloadPU = true;
        processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName();
    } else {
        processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName();
        if (beanLevelProperties.getContextProperties().getProperty("pu.download", "true").equalsIgnoreCase("true")) {
            downloadPU = true;
        }
    }
    if (beanLevelProperties != null) {
        processingUnitContainerProviderClass = beanLevelProperties.getContextProperties().getProperty(ProcessingUnitContainerProvider.CONTAINER_CLASS_PROP, processingUnitContainerProviderClass);
    }
    if (downloadPU) {
        String deployName = puName + "_" + clusterInfo.getRunningNumberOffset1();
        String deployedProcessingUnitsLocation = workLocation.getAbsolutePath() + "/processing-units";
        int uuid = Math.abs(new Random().nextInt());
        deployPath = new File(deployedProcessingUnitsLocation + "/" + deployName.replace('.', '_') + "_" + uuid);
        FileSystemUtils.deleteRecursively(deployPath);
        deployPath.mkdirs();
        // backward compatible
        beanLevelProperties.getContextProperties().setProperty("jee.deployPath", deployPath.getAbsolutePath());
        beanLevelProperties.getContextProperties().setProperty("dotnet.deployPath", deployPath.getAbsolutePath());
        beanLevelProperties.getContextProperties().setProperty(DeployableProcessingUnitContainerProvider.CONTEXT_PROPERTY_DEPLOY_PATH, deployPath.getAbsolutePath());
        try {
            if (isOnGsmHost()) {
                copyPu(puPath, deployPath);
            } else {
                long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath, new File(deployedProcessingUnitsLocation));
                logDownloadSize(size);
            }
        } catch (MalformedURLException mle) {
            logger.warn("Could not determine if GSC and GSM are on the same host", mle);
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath, new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        } catch (UnknownHostException unhe) {
            logger.warn("Could not determine if GSC and GSM are on the same host", unhe);
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath, new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        } catch (RemoteException re) {
            logger.warn("Could not determine if GSC and GSM are on the same host", re);
            long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath, new File(deployedProcessingUnitsLocation));
            logDownloadSize(size);
        }
        // go over listed files that needs to be resolved with properties
        for (Map.Entry entry : beanLevelProperties.getContextProperties().entrySet()) {
            String key = (String) entry.getKey();
            if (key.startsWith("com.gs.resolvePlaceholder")) {
                String path = (String) entry.getValue();
                File input = new File(deployPath, path);
                if (logger.isDebugEnabled()) {
                    logger.debug("Resolving placeholder for file [" + input.getAbsolutePath() + "]");
                }
                BeanLevelPropertiesUtils.resolvePlaceholders(beanLevelProperties, input);
            }
        }
    }
    boolean sharedLibEnabled;
    if (beanLevelProperties.getContextProperties().containsKey("pu.shared-lib.enable")) {
        sharedLibEnabled = beanLevelProperties.getContextProperties().getProperty("pu.shared-lib").equals("true");
    } else {
        sharedLibEnabled = System.getProperty("com.gs.pu.shared-lib.enable", "false").equals("true");
    }
    final boolean disableManifestClassPathJars = Boolean.getBoolean("com.gs.pu.manifest.classpath.disable");
    final boolean disableManifestClassPathCommonPuJars = Boolean.getBoolean("com.gs.pu.manifest.classpath.common.disable");
    // this is used to inject the manifest jars to the webapp classloader (if exists)
    List<URL> manifestClassPathJars = new ArrayList<URL>();
    CommonClassLoader commonClassLoader = CommonClassLoader.getInstance();
    // handles class loader libraries
    if (downloadPU) {
        List<URL> libUrls = new ArrayList<URL>();
        File libDir = new File(deployPath, "lib");
        if (libDir.exists()) {
            File[] libFiles = BootIOUtils.listFiles(libDir);
            for (File libFile : libFiles) {
                libUrls.add(libFile.toURI().toURL());
            }
        }
        if (!disableManifestClassPathJars) {
            File manifestFile = new File(deployPath, JarFile.MANIFEST_NAME);
            if (manifestFile.isFile()) {
                try {
                    InputStream manifestStream = new FileInputStream(manifestFile);
                    manifestClassPathJars = getManifestClassPathJars(puName, manifestStream);
                    libUrls.addAll(manifestClassPathJars);
                } catch (IOException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(failedReadingManifest(puName), e);
                    }
                }
            }
        }
        // add to common class loader
        List<URL> sharedlibUrls = new ArrayList<URL>();
        File sharedlibDir = new File(deployPath, "shared-lib");
        if (sharedlibDir.exists()) {
            File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir);
            for (File sharedlibFile : sharedlibFiles) {
                sharedlibUrls.add(sharedlibFile.toURI().toURL());
            }
        }
        sharedlibDir = new File(deployPath, "WEB-INF/shared-lib");
        if (sharedlibDir.exists()) {
            File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir);
            for (File sharedlibFile : sharedlibFiles) {
                sharedlibUrls.add(sharedlibFile.toURI().toURL());
            }
        }
        if (sharedLibEnabled) {
            ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL());
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader " + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
            commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Common Class Loader " + sharedlibUrls));
            }
        } else {
            if (sharedlibUrls.size() > 0) {
                logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'");
            }
            libUrls.addAll(sharedlibUrls);
            // add pu-common jar files
            String gsLibOpt = System.getProperty(Locator.GS_LIB_OPTIONAL);
            String gsPuCommon = System.getProperty("com.gs.pu-common", gsLibOpt + "pu-common");
            final String gsLibOptSecurity = System.getProperty(Locator.GS_LIB_OPTIONAL_SECURITY, gsLibOpt + "security");
            libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsPuCommon, gsLibOptSecurity })));
            if (ScalaIdentifier.isScalaLibInClassPath()) {
                String gsLibPlatform = System.getProperty(Locator.GS_LIB_PLATFORM);
                // note that we assume BootUtil.toURLs does not work recursively here
                // i.e, only gs-openspaces-scala.jar will be added and not all the files under /lib
                String gsLibPlatformScala = gsLibPlatform + "scala";
                libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsLibPlatformScala })));
            }
            if (!disableManifestClassPathJars && !disableManifestClassPathCommonPuJars) {
                URLClassLoader urlClassLoader = new URLClassLoader(BootUtil.toURLs(new String[] { gsPuCommon }), null);
                InputStream puCommonManifestMF = urlClassLoader.getResourceAsStream(JarFile.MANIFEST_NAME);
                if (puCommonManifestMF != null) {
                    List<URL> manifestClassPathComonPuJars = getManifestClassPathJars(puName, puCommonManifestMF);
                    manifestClassPathJars.addAll(manifestClassPathComonPuJars);
                    libUrls.addAll(manifestClassPathComonPuJars);
                }
            }
            ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL());
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader " + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
        }
        try {
            prepareWebApplication(deployPath, clusterInfo, beanLevelProperties);
        } catch (Exception e) {
            throw new CannotCreateContainerException("Failed to bootstrap web application", e);
        }
    } else {
        // add to service class loader
        List<URL> libUrls = new ArrayList<URL>();
        WebsterFile libDir = new WebsterFile(new URL(codeserver + puPath + "/lib"));
        File[] libFiles = libDir.listFiles();
        for (int i = 0; i < libFiles.length; i++) {
            libUrls.add(new URL(codeserver + puPath + "/lib/" + libFiles[i].getName()));
        }
        if (!disableManifestClassPathJars) {
            InputStream manifestStream = readManifestFromCodeServer(puName, puPath, codeserver, workLocation);
            if (manifestStream != null) {
                manifestClassPathJars = getManifestClassPathJars(puName, manifestStream);
                libUrls.addAll(manifestClassPathJars);
            }
        }
        // add to common class loader
        WebsterFile sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/shared-lib"));
        File[] sharedlibFiles = sharedlibDir.listFiles();
        List<URL> sharedlibUrls = new ArrayList<URL>();
        for (File sharedlibFile : sharedlibFiles) {
            sharedlibUrls.add(new URL(codeserver + puPath + "/shared-lib/" + sharedlibFile.getName()));
        }
        sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/WEB-INF/shared-lib"));
        sharedlibFiles = sharedlibDir.listFiles();
        for (File sharedlibFile : sharedlibFiles) {
            sharedlibUrls.add(new URL(codeserver + puPath + "/WEB-INF/shared-lib/" + sharedlibFile.getName()));
        }
        if (sharedLibEnabled) {
            ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/"));
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader " + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
            commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Common Class Loader " + sharedlibUrls));
            }
        } else {
            if (sharedlibUrls.size() > 0) {
                logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'");
            }
            libUrls.addAll(sharedlibUrls);
            ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/"));
            ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()]));
            if (logger.isDebugEnabled()) {
                logger.debug(logMessage("Service Class Loader " + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs())));
            }
        }
    }
    // handle mule os if there is one class loader
    try {
        contextClassLoader.loadClass("org.mule.api.MuleContext");
        ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { Environment.getHomeDirectory() + "/lib/optional/openspaces/mule-os.jar" }));
    } catch (Throwable e) {
    }
    factory = createContainerProvider(processingUnitContainerProviderClass);
    if (factory instanceof DeployableProcessingUnitContainerProvider) {
        ((DeployableProcessingUnitContainerProvider) factory).setDeployPath(deployPath);
    }
    if (factory instanceof ClassLoaderAwareProcessingUnitContainerProvider) {
        ((ClassLoaderAwareProcessingUnitContainerProvider) factory).setClassLoader(contextClassLoader);
    }
    if (factory instanceof JeeProcessingUnitContainerProvider) {
        ((JeeProcessingUnitContainerProvider) factory).setManifestUrls(manifestClassPathJars);
    }
    // only load the spring xml file if it is not a web application (if it is a web application, we will load it with the Bootstrap servlet context loader)
    if (webXml == null && factory instanceof ApplicationContextProcessingUnitContainerProvider) {
        if (StringUtils.hasText(springXml)) {
            // re-load the pu.xml to support "hot-deploy" (refresh)
            if (springXml.contains("os-gateway:")) {
                String deployPath = beanLevelProperties.getContextProperties().getProperty("deployPath");
                if (StringUtils.hasText(deployPath)) {
                    String newSpringXml = readFile(deployPath + "/META-INF/spring/pu.xml");
                    if (StringUtils.hasText(newSpringXml)) {
                        //override with new one
                        springXml = newSpringXml;
                    }
                }
            }
            Resource resource = new ByteArrayResource(springXml.getBytes());
            ((ApplicationContextProcessingUnitContainerProvider) factory).addConfigLocation(resource);
        }
    }
    if (factory instanceof ClusterInfoAware) {
        ((ClusterInfoAware) factory).setClusterInfo(clusterInfo);
    }
    if (factory instanceof BeanLevelPropertiesAware) {
        ((BeanLevelPropertiesAware) factory).setBeanLevelProperties(beanLevelProperties);
    }
    container = factory.createContainer();
    // set the context class loader to the web app class loader if there is one
    // this menas that from now on, and the exported service, will use the context class loader
    ClassLoader webAppClassLoader = SharedServiceData.removeWebAppClassLoader(clusterInfo.getUniqueName());
    if (webAppClassLoader != null) {
        contextClassLoader = webAppClassLoader;
    }
    Thread.currentThread().setContextClassLoader(contextClassLoader);
    buildMembersAliveIndicators();
    buildUndeployingEventListeners();
    buildDumpProcessors();
    ArrayList<Object> serviceDetails = buildServiceDetails();
    buildServiceMonitors();
    buildInvocableServices();
    this.puDetails = new PUDetails(context.getParentServiceID(), clusterInfo, beanLevelProperties, serviceDetails.toArray(new Object[serviceDetails.size()]));
    if (container instanceof ApplicationContextProcessingUnitContainer) {
        ApplicationContext applicationContext = ((ApplicationContextProcessingUnitContainer) container).getApplicationContext();
        // inject the application context to all the monitors and schedule them
        // currently use the number of threads in relation to the number of monitors
        int numberOfThreads = watchTasks.size() / 5;
        if (numberOfThreads == 0) {
            numberOfThreads = 1;
        }
        executorService = Executors.newScheduledThreadPool(numberOfThreads);
        for (WatchTask watchTask : watchTasks) {
            if (watchTask.getMonitor() instanceof ApplicationContextMonitor) {
                ((ApplicationContextMonitor) watchTask.getMonitor()).setApplicationContext(applicationContext);
            }
            executorService.scheduleAtFixedRate(watchTask, watchTask.getMonitor().getPeriod(), watchTask.getMonitor().getPeriod(), TimeUnit.MILLISECONDS);
        }
    }
}
Example 83
Project: kaa-master  File: AdminClient.java View source code
private EndpointNotificationDto sendUnicastNotification(NotificationDto notification, String clientKeyHash, ByteArrayResource resource) throws Exception {
    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("notification", notification);
    params.add("endpointKeyHash", clientKeyHash);
    params.add("file", resource);
    return restTemplate.postForObject(restTemplate.getUrl() + "sendUnicastNotification", params, EndpointNotificationDto.class);
}
Example 84
Project: rayo-server-master  File: PropertiesBasedGatewayStorageServiceTest.java View source code
@Before
public void setup() throws Exception {
    storageService = new DefaultGatewayStorageService();
    storageService.setStore(new PropertiesBasedDatastore(new ByteArrayResource(new byte[] {})));
    loadBalancer = new RoundRobinLoadBalancer();
    loadBalancer.setStorageService(storageService);
}
Example 85
Project: bootdragon-master  File: PreviewGif.java View source code
/**
	 * @return the GIF data as a {@link Resource}.
	 */
public Resource asResource() {
    return new ByteArrayResource(this.bytes) {

        @Override
        public String getFilename() {
            return "preview.gif";
        }
    };
}
Example 86
Project: paxml-master  File: InMemoryResource.java View source code
@Override
public Resource getSpringResource() {
    return new ByteArrayResource(array);
}
Example 87
Project: easylocate-master  File: TestInvalidResourceBeanDefinitionParser.java View source code
private void loadContext(String attributes) {
    String config = HEADER + String.format(TEMPLATE, attributes) + FOOTER;
    context = new GenericXmlApplicationContext(new ByteArrayResource(config.getBytes()));
}
Example 88
Project: RMT-master  File: Notification.java View source code
public InputStreamSource getInputStreamSource() {
    return new ByteArrayResource(data);
}
Example 89
Project: spring-android-master  File: ResourceHttpMessageConverter.java View source code
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
    return new ByteArrayResource(body);
}
Example 90
Project: spring-security-oauth-master  File: InvalidResourceBeanDefinitionParserTests.java View source code
private void loadContext(String attributes) {
    String config = HEADER + String.format(TEMPLATE, attributes) + FOOTER;
    context = new GenericXmlApplicationContext(new ByteArrayResource(config.getBytes()));
}
Example 91
Project: wildfly-camel-master  File: SpringCamelContextFactory.java View source code
/**
     * Create a {@link SpringCamelContext} list from the given bytes
     */
public static List<SpringCamelContext> createCamelContextList(byte[] bytes, ClassLoader classsLoader) throws Exception {
    return createCamelContextList(new ByteArrayResource(bytes), classsLoader);
}
Example 92
Project: spring-data-document-examples-master  File: ResourceHttpMessageConverter.java View source code
public Resource read(Class<? extends Resource> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    byte[] body = FileCopyUtils.copyToByteArray(inputMessage.getBody());
    return new ByteArrayResource(body);
}
Example 93
Project: apis-master  File: AuthorizationServerFilterTest.java View source code
private MockFilterChain doCallFilter(VerifyTokenResponse recorderdResponse, MockHttpServletResponse response) throws IOException, ServletException {
    return doCallFilter(new Resource[] { new ByteArrayResource(mapper.writeValueAsString(recorderdResponse).getBytes(), "json") }, response);
}
Example 94
Project: javasousuo-master  File: ResourceTest.java View source code
@Test
public void testByteArrayResource() {
    Resource resource = new ByteArrayResource("Hello World!".getBytes());
    if (resource.exists()) {
        dumpStream(resource);
    }
    Assert.assertEquals(false, resource.isOpen());
}
Example 95
Project: uPortal-master  File: IdentityImportExportTest.java View source code
protected void runSql(final String sql) {
    if (simpleJdbcTemplate == null) {
        simpleJdbcTemplate = new JdbcTemplate(dataSource);
    }
    JdbcTestUtils.executeSqlScript(simpleJdbcTemplate, new ByteArrayResource(sql.getBytes()), false);
}
Example 96
Project: eucalyptus-master  File: ServiceContextManager.java View source code
private static Resource createConfigResource(final ComponentId componentId, final String outString) {
    Logs.extreme().trace("===================================");
    Logs.extreme().trace(outString);
    Logs.extreme().trace("===================================");
    return new ByteArrayResource(outString.getBytes(), componentId.getServiceModelFileName());
}
Example 97
Project: jetstream-master  File: MongoDataStoreReader.java View source code
private int loadBeanDefinitionsFromString(String beanDefinition) {
    AbstractBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(this.getRegistry());
    Resource resource = new ByteArrayResource(beanDefinition.getBytes());
    int count = beanDefinitionReader.loadBeanDefinitions(resource);
    return count;
}
Example 98
Project: spring-social-facebook-master  File: PageTemplateTest.java View source code
private Resource getUploadResource(final String filename, String content) {
    Resource video = new ByteArrayResource(content.getBytes()) {

        public String getFilename() throws IllegalStateException {
            return filename;
        }

        ;
    };
    return video;
}
Example 99
Project: spring-social-weibo-master  File: TimelineTemplateTest.java View source code
private Resource createResource() {
    Resource media = new ByteArrayResource("data".getBytes()) {

        @Override
        public String getFilename() throws IllegalStateException {
            return "photo.jpg";
        }
    };
    return media;
}
Example 100
Project: spring-social-twitter-master  File: TimelineTemplateTest.java View source code
// private helper
private Resource getUploadResource(final String filename, String content) {
    Resource resource = new ByteArrayResource(content.getBytes()) {

        @Override
        public String getFilename() throws IllegalStateException {
            return filename;
        }

        ;
    };
    return resource;
}
Example 101
Project: spring-twitter-master  File: TimelineTemplateTest.java View source code
// private helper
private Resource getUploadResource(final String filename, String content) {
    Resource resource = new ByteArrayResource(content.getBytes()) {

        @Override
        public String getFilename() throws IllegalStateException {
            return filename;
        }

        ;
    };
    return resource;
}