List of usage examples for org.springframework.core.io ByteArrayResource ByteArrayResource
public ByteArrayResource(byte[] byteArray)
From source file:org.kuali.coeus.common.impl.mail.KcEmailServiceImpl.java
public void sendEmailWithAttachments(String from, Set<String> toAddresses, String subject, Set<String> ccAddresses, Set<String> bccAddresses, String body, boolean htmlMessage, List<EmailAttachment> attachments) { if (mailSender != null) { if (CollectionUtils.isEmpty(toAddresses) && CollectionUtils.isEmpty(ccAddresses) && CollectionUtils.isEmpty(bccAddresses)) { return; }//from w w w .j av a 2 s.c om MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = null; try { helper = new MimeMessageHelper(message, true, DEFAULT_ENCODING); helper.setFrom(from); if (StringUtils.isNotBlank(subject)) { helper.setSubject(subject); } else { LOG.warn("Sending message with empty subject."); } if (isEmailTestEnabled()) { helper.setText(getTestMessageBody(body, toAddresses, ccAddresses, bccAddresses), true); String toAddress = getEmailNotificationTestAddress(); if (StringUtils.isNotBlank(getEmailNotificationTestAddress())) { helper.addTo(toAddress); } } else { helper.setText(body, htmlMessage); if (CollectionUtils.isNotEmpty(toAddresses)) { for (String toAddress : toAddresses) { try { helper.addTo(toAddress); } catch (Exception ex) { LOG.warn("Could not set to address:", ex); } } } if (CollectionUtils.isNotEmpty(ccAddresses)) { for (String ccAddress : ccAddresses) { try { helper.addCc(ccAddress); } catch (Exception ex) { LOG.warn("Could not set to address:", ex); } } } if (CollectionUtils.isNotEmpty(bccAddresses)) { for (String bccAddress : bccAddresses) { try { helper.addBcc(bccAddress); } catch (Exception ex) { LOG.warn("Could not set to address:", ex); } } } } if (CollectionUtils.isNotEmpty(attachments)) { for (EmailAttachment attachment : attachments) { try { helper.addAttachment(attachment.getFileName(), new ByteArrayResource(attachment.getContents()), attachment.getMimeType()); } catch (Exception ex) { LOG.warn("Could not set to address:", ex); } } } executorService.execute(() -> mailSender.send(message)); } catch (MessagingException ex) { LOG.error("Failed to create mime message helper.", ex); } } else { LOG.info( "Failed to send email due to inability to obtain valid email mailSender, please check your configuration."); } }
From source file:org.kuali.kra.service.impl.KcEmailServiceImpl.java
public void sendEmailWithAttachments(String from, Set<String> toAddresses, String subject, Set<String> ccAddresses, Set<String> bccAddresses, String body, boolean htmlMessage, List<EmailAttachment> attachments) { JavaMailSender sender = createSender(); if (sender != null) { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = null; try {//from w w w .j ava 2 s . co m helper = new MimeMessageHelper(message, true, DEFAULT_ENCODING); helper.setFrom(from); if (CollectionUtils.isNotEmpty(toAddresses)) { for (String toAddress : toAddresses) { helper.addTo(toAddress); } } if (StringUtils.isNotBlank(subject)) { helper.setSubject(subject); } else { LOG.warn("Sending message with empty subject."); } helper.setText(body, htmlMessage); if (CollectionUtils.isNotEmpty(ccAddresses)) { for (String ccAddress : ccAddresses) { helper.addCc(ccAddress); } } if (CollectionUtils.isNotEmpty(bccAddresses)) { for (String bccAddress : bccAddresses) { helper.addBcc(bccAddress); } } if (CollectionUtils.isNotEmpty(attachments)) { for (EmailAttachment attachment : attachments) { helper.addAttachment(attachment.getFileName(), new ByteArrayResource(attachment.getContents()), attachment.getMimeType()); } } sender.send(message); } catch (MessagingException ex) { LOG.error("Failed to create mime message helper.", ex); } catch (Exception e) { LOG.error("Failed to send email.", e); } } else { LOG.info( "Failed to send email due to inability to obtain valid email sender, please check your configuration."); } }
From source file:org.ojbc.web.portal.services.SearchResultConverterTest.java
@Before public void setup() { xsltTransformerService = mock(XsltTransformerService.class); applicationContext = mock(ApplicationContext.class); unit = new SearchResultConverter(); unit.searchResultXsl = new ByteArrayResource("search xsl".getBytes()) { public java.net.URL getURL() throws IOException { return new URL("http://something/dontCare"); };/* w w w. j a va 2 s . c o m*/ }; unit.incidentSearchResultXsl = unit.searchResultXsl; unit.vehicleSearchResultXsl = unit.searchResultXsl; unit.xsltTransformerService = xsltTransformerService; unit.setApplicationContext(applicationContext); sourceXmlCaptor = ArgumentCaptor.forClass(SAXSource.class); sourceXslCaptor = ArgumentCaptor.forClass(SAXSource.class); paramsCaptor = ArgumentCaptor.forClass(Map.class); HashMap<String, String> searchDetailToXsl = new HashMap<String, String>(); searchDetailToXsl.put("System", "searchDetail-system.xsl"); searchDetailToXsl.put("System 2", "searchDetail-system2.xsl"); unit.searchDetailToXsl = searchDetailToXsl; }
From source file:org.ojbc.web.portal.services.SearchResultConverterTest.java
@Test public void convertDetailSearchResultLoadsXslPassedInAndDoesNotPassAnyParams() throws Exception { Resource resource = new ByteArrayResource("someSystem xsl".getBytes()) { public java.net.URL getURL() throws IOException { return new URL("http://something/dontCare"); };/* ww w . java2 s. c om*/ }; unit.searchDetailToXsl.put("someSystemName", "someSystemName.xsl"); when(applicationContext.getResource("classpath:xsl/someSystemName.xsl")).thenReturn(resource); when(xsltTransformerService.transform(sourceXmlCaptor.capture(), sourceXslCaptor.capture(), paramsCaptor.capture())).thenReturn("some transformed content"); unit.convertDetailSearchResult("some search content", "someSystemName", null); assertThat(getContentFromSAXSource(sourceXmlCaptor.getValue()), is("some search content")); assertThat(getContentFromSAXSource(sourceXslCaptor.getValue()), is("someSystem xsl")); assertThat(paramsCaptor.getValue(), nullValue()); }
From source file:org.ojbc.web.portal.services.SearchResultConverterTest.java
@Test public void resourcesLoadOnceThenCached() { when(applicationContext.getResource("classpath:xsl/searchDetail-system.xsl")) .thenReturn(new ByteArrayResource("".getBytes())); Resource firstResource = unit.getResource("System"); Resource secondResource = unit.getResource("System"); verify(applicationContext, Mockito.times(1)).getResource("classpath:xsl/searchDetail-system.xsl"); assertSame(firstResource, secondResource); }
From source file:org.ojbc.web.portal.services.SearchResultConverterTest.java
@Test public void filterXml() throws Exception { unit.personFilterXsl = new ByteArrayResource("some xsl".getBytes()) { public java.net.URL getURL() throws IOException { return new URL("http://something/dontCare"); };/*from ww w.ja v a 2 s .c o m*/ }; unit.personFilterCleanupMergedXsl = new ByteArrayResource("some xsl".getBytes()) { public java.net.URL getURL() throws IOException { return new URL("http://something/dontCare"); }; }; String xmlContent = "xml content"; PersonFilterCommand personFilterCommand = new PersonFilterCommand(); when(xsltTransformerService.transform(sourceXmlCaptor.capture(), sourceXslCaptor.capture(), paramsCaptor.capture())).thenReturn("some transformed content"); String expectedResult = unit.filterXml(xmlContent, personFilterCommand); assertThat(expectedResult, is("some transformed content")); // assertThat(getContentFromSAXSource(sourceXmlCaptor.getValue()), is("xml content")); // we have a 2-stage filter. The input to the second stage is the output from the first stage, // therefore, we have sourceXmlCaptor value of some transformed content going into the second stage: assertThat(getContentFromSAXSource(sourceXmlCaptor.getValue()), is("some transformed content")); assertThat(getContentFromSAXSource(sourceXslCaptor.getValue()), is("some xsl")); }
From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java
protected Resource getResource(final String text) { if (text == null) return new ByteArrayResource(new byte[0]); return new ByteArrayResource(text.getBytes()); }
From source file:org.openspaces.admin.application.ApplicationFileDeployment.java
private static ApplicationConfig readConfigFromZipFile(final File directoryOrZip, String applicationFile) throws AdminException, BeansException { byte[] buffer = FileUtils.unzipFileToMemory(applicationFile, directoryOrZip, MAX_XML_FILE_SIZE); Resource resource = new ByteArrayResource(buffer); return getSpringBeanFromResource(resource, ApplicationConfig.class); }
From source file:org.openspaces.pu.container.servicegrid.deploy.Deploy.java
public OperationalString buildOperationalString(String[] args) throws Exception { if (args.length == 0) { throw new IllegalArgumentException("The pu name must be defined"); }/*w ww. jav a 2s.com*/ String puPath = args[args.length - 1]; File puFile = new File(puPath); String puName = puFile.getName().replace(' ', '_'); // override pu name allows to change the actual pu name deployed from the on under deploy directory String overridePuName = puName; boolean deletePUFile = false; if (puFile.exists() && puFile.isDirectory()) { // this is a directory, jar it up and prepare it for upload File zipPUFile = new File(System.getProperty("java.io.tmpdir") + "/" + puName + ".zip"); info("Deploying a directory [" + puFile.getAbsolutePath() + "], zipping it into [" + zipPUFile.getAbsolutePath() + "]"); PUZipUtils.zip(puFile, zipPUFile); puFile = zipPUFile; deletePUFile = true; } if (puFile.getName().endsWith(".zip") || puFile.getName().endsWith(".jar") || puFile.getName().endsWith(".war")) { if (!puFile.exists()) { throw new IllegalArgumentException( "File [" + puFile.getAbsolutePath() + "] not found and can't be deployed"); } overridePuName = puFile.getName().substring(0, puFile.getName().length() - 4).replace(' ', '_'); puPath = overridePuName; } CommandLineParser.Parameter[] params = CommandLineParser.parse(args, args.length - 1); RequiredDependencies instanceDeploymentDependencies = new RequiredDependencies(); RequiredDependencies instanceStartDependencies = new RequiredDependencies(); // check if we have a groups parameter and timeout parameter for (CommandLineParser.Parameter param : params) { if (param.getName().equalsIgnoreCase(KEY_GROUPS)) { setGroups(param.getArguments()); } if (param.getName().equalsIgnoreCase(KEY_LOCATORS)) { StringBuilder sb = new StringBuilder(); for (String arg : param.getArguments()) { sb.append(arg).append(','); } setLocators(sb.toString()); } if (param.getName().equalsIgnoreCase(KEY_TIMEOUT)) { setLookupTimeout(Integer.valueOf(param.getArguments()[0])); } if (param.getName().equalsIgnoreCase(KEY_OVERRIDE_NAME)) { overridePuName = param.getArguments()[0]; } if (param.getName().equalsIgnoreCase(KEY_DEPLOY_TIMEOUT)) { setDeployTimeout(Long.valueOf(param.getArguments()[0])); } if (RequiredDependenciesCommandLineParser.isInstanceDeploymentDependencies(param)) { instanceDeploymentDependencies = RequiredDependenciesCommandLineParser .convertCommandlineParameterToInstanceDeploymentDependencies(param); } if (RequiredDependenciesCommandLineParser.isInstanceStartDependencies(param)) { instanceStartDependencies = RequiredDependenciesCommandLineParser .convertCommandlineParameterToInstanceStartDependencies(param); } if (param.getName().equalsIgnoreCase(KEY_APPLICATION_NAME)) { setApplicationName(param.getArguments()[0]); } } info("Deploying [" + puName + "] with name [" + overridePuName + "] under groups " + Arrays.toString(getGroups()) + " and locators " + Arrays.toString(getLocators())); initGSM(); initDeployAdmin(); // check if the pu to deploy is an actual file on the file system and ends with jar, zip or war. if (puFile.exists() && (puFile.getName().endsWith(".zip") || puFile.getName().endsWith(".jar") || puFile.getName().endsWith(".war"))) { try { if (isOnGsmHost()) { // the client is on the same host as the gsm. // we can simply copy the pu instead of uploading it. copyPu(puPath, puFile); } else { // we deploy a jar/zip/war file, upload it to the GSM uploadPU(puPath, puFile); } } catch (UnknownHostException uhe) { // fall back to upload anyway logger.warn("Could not determine if client and GSM[" + gsm.getGSAServiceID() + "] are on the same " + "host", uhe); uploadPU(puPath, puFile); } catch (RemoteException re) { // fall back to upload anyway logger.warn("Could not determine if client and GSM[" + gsm.getGSAServiceID() + "] are on the same " + "host", re); uploadPU(puPath, puFile); } if (deletePUFile) { puFile.delete(); } } if (!gsm.hasPUUnderDeploy(puPath)) { throw new ProcessingUnitNotFoundException(puName, gsm); } String codeserver = getCodebase(deployAdmin); if (logger.isDebugEnabled()) { logger.debug("Using codeserver [" + codeserver + "]"); } //list remote files, only works with webster URL root = new URL(codeserver); BeanLevelProperties beanLevelProperties = new BeanLevelProperties(); URL puPropsURL = new URL(root, puPath + "/META-INF/spring/pu.properties"); try { InputStream is = puPropsURL.openStream(); if (is != null) { beanLevelProperties.getContextProperties().load(is); is.close(); } } catch (Exception e) { // ignore, no file } puPropsURL = new URL(root, puPath + "/pu.properties"); try { InputStream is = puPropsURL.openStream(); if (is != null) { beanLevelProperties.getContextProperties().load(is); is.close(); } } catch (Exception e) { // ignore, no file } beanLevelProperties = BeanLevelPropertiesParser.parse(beanLevelProperties, params); //read pu xml String puString = ""; try { puString = readFile(root, puPath, "/META-INF/spring/pu.xml"); } catch (IOException e) { logger.debug("Failed to find puPath " + puPath, e); // ignore, it might be ok for war files } if (logger.isDebugEnabled()) { logger.debug("Using PU xml [" + puString + "]"); } boolean slaInPu = true; Resource resource; // check to see if sla was passed as a parameter String slaString = puString; for (CommandLineParser.Parameter param : params) { if (param.getName().equalsIgnoreCase(KEY_SLA)) { String slaLocation = param.getArguments()[0]; info("Loading SLA from [" + slaLocation + "]"); resource = new DefaultResourceLoader() { // override the default load from the classpath to load from the file system @Override protected Resource getResourceByPath(String path) { return new FileSystemResource(path); } }.getResource(slaLocation); InputStreamReader reader = new InputStreamReader(resource.getInputStream()); slaString = FileCopyUtils.copyToString(reader); reader.close(); slaInPu = false; } } if (slaString == puString) { // no sla passed as a parameter, try and load from default locations try { slaString = readFile(root, puPath, "/META-INF/spring/sla.xml"); slaInPu = false; } catch (IOException e) { // no sla string found try { slaString = readFile(root, puPath, "/sla.xml"); slaInPu = false; } catch (IOException e1) { // no sla string found } } } //get sla from pu string SLA sla = new SLA(); if (StringUtils.hasText(slaString)) { resource = new ByteArrayResource(slaString.getBytes()); if (slaInPu) { XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(resource); // TODO: Need to find how to do it // Map<String, PropertyResourceConfigurer> map = xmlBeanFactory.getBeansOfType(PropertyResourceConfigurer.class); // for (PropertyResourceConfigurer cfg : map.values()) { // cfg.postProcessBeanFactory(xmlBeanFactory); // } try { sla = (SLA) xmlBeanFactory.getBean("SLA"); } catch (NoSuchBeanDefinitionException e) { info("SLA Not Found in PU. Using Default SLA."); sla = new SLA(); } } else { // if we have specific sla file, load it as usual, so we can have deploy properties / system properties injected to it ProcessingUnitContainerConfig config = new ProcessingUnitContainerConfig(); config.setBeanLevelProperties(beanLevelProperties); ResourceApplicationContext applicationContext = new ResourceApplicationContext( new Resource[] { resource }, null, config); // start the application context applicationContext.refresh(); try { sla = (SLA) applicationContext.getBean("SLA"); } catch (NoSuchBeanDefinitionException e) { throw new IllegalArgumentException("Failed to find SLA from in [" + slaString + "]"); } finally { applicationContext.close(); } } } ClusterInfo clusterInfo = ClusterInfoParser.parse(params); if (clusterInfo != null) { // override specific cluster info parameters on the SLA if (clusterInfo.getSchema() != null && clusterInfo.getSchema().length() > 0) { info("Overriding SLA cluster schema with [" + clusterInfo.getSchema() + "]"); sla.setClusterSchema(clusterInfo.getSchema()); } if (clusterInfo.getNumberOfInstances() != null) { info("Overriding SLA numberOfInstances with [" + clusterInfo.getNumberOfInstances() + "]"); sla.setNumberOfInstances(clusterInfo.getNumberOfInstances()); if (clusterInfo.getNumberOfBackups() == null) { info("Overriding SLA numberOfBackups with [" + clusterInfo.getNumberOfBackups() + "]"); sla.setNumberOfBackups(0); } else { info("Overriding SLA numberOfBackups with [" + clusterInfo.getNumberOfBackups() + "]"); sla.setNumberOfBackups(clusterInfo.getNumberOfBackups()); } } } for (CommandLineParser.Parameter param : params) { if (param.getName().equalsIgnoreCase(KEY_REQUIRES_ISOLATION)) { String requiresIsolation = param.getArguments()[0]; sla.setRequiresIsolation(Boolean.parseBoolean(requiresIsolation)); info("Overriding SLA requiresIsolation with [" + requiresIsolation + "]"); } if (param.getName().equalsIgnoreCase(KEY_MAX_INSTANCES_PER_VM)) { String maxInstancePerVm = param.getArguments()[0]; sla.setMaxInstancesPerVM(Integer.valueOf(maxInstancePerVm)); info("Overriding SLA maxInstancesPerVM with [" + maxInstancePerVm + "]"); } if (param.getName().equalsIgnoreCase(KEY_MAX_INSTANCES_PER_MACHINE)) { String maxInstancePerMachine = param.getArguments()[0]; sla.setMaxInstancesPerMachine(Integer.valueOf(maxInstancePerMachine)); info("Overriding SLA maxInstancesPerMachine with [" + maxInstancePerMachine + "]"); } if (param.getName().equalsIgnoreCase(KEY_MAX_INSTANCES_PER_ZONE)) { Map<String, Integer> map = new HashMap<String, Integer>(); for (String arg : param.getArguments()) { map.putAll(ZoneHelper.parse(arg)); } sla.setMaxInstancesPerZone(map); info("Overriding SLA maxInstancesPerZone with [" + ZoneHelper.unparse(map) + "]"); } if (param.getName().equalsIgnoreCase(KEY_ZONES)) { for (String arg : param.getArguments()) { sla.getRequirements().add(new ZoneRequirement(arg)); info("Adding SLA required zone with [" + arg + "]"); } } if (param.getName().equalsIgnoreCase(KEY_PRIMARY_ZONE)) { String primaryZone = param.getArguments()[0]; sla.setPrimaryZone(primaryZone); info("Overriding SLA primaryZone with [" + primaryZone + "]"); } } if (logger.isDebugEnabled()) { logger.debug("Using SLA " + sla); } processSecurityParameters(beanLevelProperties, params); //Get elastic properties Map<String, String> elasticProperties = new HashMap<String, String>(); for (CommandLineParser.Parameter param : params) { if (param.getName().equalsIgnoreCase(KEY_ELASTIC_PROPERTIES)) { for (String argument : param.getArguments()) { int indexOfEqual = argument.indexOf("="); String name = argument.substring(0, indexOfEqual); String value = argument.substring(indexOfEqual + 1); elasticProperties.put(name, value); } } } //get pu type String puType = guessProcessingUnitType(puPath, puFile, root, puString, sla, beanLevelProperties); beanLevelProperties.getContextProperties().put("pu.type", puType); //deploy to sg return loadDeployment(puString, codeserver, sla, puPath, overridePuName, beanLevelProperties, elasticProperties, instanceDeploymentDependencies, instanceStartDependencies, applicationName); }
From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java
private void startPU(String springXml) throws IOException, ClassNotFoundException { if (logger.isDebugEnabled()) { logger.debug(logMessage("Starting PU with [" + springXml + "]")); }/*from w ww . ja v a 2 s. co m*/ 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(SystemInfo.singleton().locations().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 final InputStream webXml = openUrlStream(codeserver + puPath + "/WEB-INF/web.xml"); // identify if this is a .NET one final InputStream puConfig = openUrlStream(codeserver + puPath + "/pu.config"); // identify if this is a .NET interop one final InputStream puInteropConfig = openUrlStream(codeserver + puPath + "/pu.interop.config"); 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( ProcessingUnitContainerProvider.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); // fallback to download 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); // fallback to download 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); // fallback to download 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 = Locator.getLibOptional(); String gsPuCommon = System.getProperty("com.gs.pu-common", gsLibOpt + "pu-common"); final String gsLibOptSecurity = Locator.getLibOptionalSecurity(); libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsPuCommon, gsLibOptSecurity }))); if (ScalaIdentifier.isScalaLibInClassPath()) { String gsLibPlatform = Locator.getLibPlatform(); // 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 /* parent */); 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[] { SystemInfo.singleton().locations().lib() + "/optional/openspaces/mule-os.jar" })); } catch (Throwable e) { // no mule } //apply the following only if the pu has the rest element if (springXml.contains("<os-core:rest")) { String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties); // pre load the jetty server class so the static shutdown thread will be loaded under it String[] classesToLoad = new String[] { "org.eclipse.jetty.server.Server" }; String jettyJars = System.getProperty("com.gigaspaces.rest.jetty", JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer)); // setup class loaders correctly try { Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance()); ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { jettyJars, SystemInfo.singleton().locations().lib() + "/platform/jetty/org.apache.jasper.glassfish-2.2.2.v201112011158.jar", SystemInfo.singleton().locations().lib() + "/optional/spring/spring-web-4.1.1.RELEASE.jar", SystemInfo.singleton().locations().lib() + "/optional/spring/spring-webmvc-4.1.1.RELEASE.jar", SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-core-2.3.0.jar", SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-databind-2.3.0.jar", SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-annotations-2.3.0.jar", SystemInfo.singleton().locations().lib() + "/platform/rest/xap-rest.jar" })); ((ServiceClassLoader) contextClassLoader) .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad)); } catch (Exception e) { throw new CannotCreateContainerException("Failed to configure class loader", e); } finally { //TODO check if we need this Thread.currentThread().setContextClassLoader(contextClassLoader); } } //apply the following only if the pu has the mapdb-blob-store element if (springXml.contains("<blob-store:mapdb-blob-store")) { String mapdbJar = System.getProperty("com.gigaspaces.blobstore.mapdb", SystemInfo.singleton().locations().lib() + "/optional/blobstore/mapdb-blobstore.jar"); Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance()); ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { mapdbJar })); Thread.currentThread().setContextClassLoader(contextClassLoader); } //apply the following only if the pu has the rocksdb-blob-store element if (springXml.contains("<blob-store:rocksdb-blob-store") || springXml.contains("class=\"com.gigaspaces.blobstore.rocksdb.RocksDBBlobStoreHandler\"")) { String rocksdbJar = System.getProperty("com.gigaspaces.blobstore.rocksdb", SystemInfo.singleton().locations().lib() + "/optional/blobstore/rocksdb-blobstore.jar"); Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance()); ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { rocksdbJar })); Thread.currentThread().setContextClassLoader(contextClassLoader); } final Map<String, String> puTags = buildPuTags(clusterInfo); MetricRegistrator puMetricRegistrator = metricManager.createRegistrator("pu", puTags); this.metricRegistrators = metricManager.registerProcessMetrics(puTags); this.metricRegistrators.add(puMetricRegistrator); for (Map.Entry<String, String> entry : puTags.entrySet()) beanLevelProperties.getContextProperties().setProperty("metrics." + entry.getKey(), entry.getValue()); //inject quiesce state changed event in order let space know to be initialized in quiesced mode if (quiesceDetails != null && quiesceDetails.getStatus() == QuiesceState.QUIESCED) { beanLevelProperties.getContextProperties().setProperty("quiesce.token", quiesceDetails.getToken().toString()); beanLevelProperties.getContextProperties().setProperty("quiesce.description", quiesceDetails.getDescription()); } factory = createContainerProvider(processingUnitContainerProviderClass); factory.setDeployPath(deployPath); factory.setClassLoader(contextClassLoader); 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)) { // GS-9350: if this is a processing unit with gateway declarations, always try to // 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)) { springXml = newSpringXml; //override with new one } } } Resource resource = new ByteArrayResource(springXml.getBytes()); ((ApplicationContextProcessingUnitContainerProvider) factory).addConfigLocation(resource); } } factory.setClusterInfo(clusterInfo); factory.setBeanLevelProperties(beanLevelProperties); factory.setMetricRegistrator(puMetricRegistrator); 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); } } }