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

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

Example 1
Project: corespring-master  File: ResourceFieldSetReaderTests.java View source code
public void testRead() throws Exception {
    Resource resource = new InputStreamResource(new ByteArrayInputStream("foo,bar,spam\nbucket,crap,man".getBytes()));
    ResourceFieldSetReader reader = new ResourceFieldSetReader(resource);
    int count = 0;
    FieldSet fieldSet;
    while ((fieldSet = reader.read()) != null) {
        count++;
        assertNotNull(fieldSet);
        assertEquals(3, fieldSet.getFieldCount());
    }
    assertEquals(2, count);
}
Example 2
Project: infovore-master  File: ApplicationConfigurationFetcher.java View source code
public ApplicationContext enrichedContext() throws IOException {
    GenericApplicationContext that = new GenericApplicationContext(applicationContext);
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(that);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    reader.loadBeanDefinitions(new InputStreamResource(getContextXml()));
    that.refresh();
    return that;
}
Example 3
Project: knorxx-master  File: KnorxxGeneratorCacheConfig.java View source code
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
    EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
    try {
        ehCacheManagerFactoryBean.setConfigLocation(new InputStreamResource(new ByteArrayInputStream(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ehcache>\n" + "    <defaultCache eternal=\"true\" maxElementsInMemory=\"100\" overflowToDisk=\"false\" />\n" + "    <cache name=\"" + GENERATOR_CACHE_NAME + "\" maxEntriesLocalHeap=\"1000\" />" + "</ehcache>").getBytes("UTF-8"))));
    } catch (UnsupportedEncodingException ex) {
        throw new IllegalStateException(ex);
    }
    return ehCacheManagerFactoryBean;
}
Example 4
Project: cas-master  File: X509CertificateCredentialJsonDeserializer.java View source code
@Override
public X509CertificateCredential deserialize(final JsonParser jp, final DeserializationContext deserializationContext) throws IOException {
    final ObjectCodec oc = jp.getCodec();
    final JsonNode node = oc.readTree(jp);
    final List<X509Certificate> certs = new ArrayList<>();
    node.findValues("certificates").forEach( n -> {
        final String cert = n.get(0).textValue();
        final byte[] data = EncodingUtils.decodeBase64(cert);
        certs.add(CertUtils.readCertificate(new InputStreamResource(new ByteArrayInputStream(data))));
    });
    final X509CertificateCredential c = new X509CertificateCredential(certs.toArray(new X509Certificate[] {}));
    return c;
}
Example 5
Project: spring-reactive-master  File: ResourceHttpMessageConverter.java View source code
private static Optional<Long> contentLength(Resource resource) {
    // Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
    if (InputStreamResource.class != resource.getClass()) {
        try {
            return Optional.of(resource.contentLength());
        } catch (IOException ignored) {
        }
    }
    return Optional.empty();
}
Example 6
Project: egd-web-master  File: MediaResource.java View source code
@RequestMapping(value = "/{fileSha}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> get(@PathVariable String fileSha) throws IOException, MimeTypeException {
    log.debug("REST request to get Media : {}", fileSha);
    try {
        Map.Entry<Properties, File> entry = service.getWithProperties(fileSha);
        Properties properties = entry.getKey();
        File file = entry.getValue();
        String mimeType = properties.getProperty("mime-type");
        StringBuilder filename = new StringBuilder(fileSha);
        String origExt = properties.getProperty("orig-extension");
        if (origExt != null) {
            filename.append(".").append(origExt);
        } else {
            try {
                MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
                MimeType mime = allTypes.forName(mimeType);
                String ext = mime.getExtension();
                filename.append(".").append(ext);
            } catch (Exception e) {
                log.error("no extension", e.getMessage());
            }
        }
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.valueOf(mimeType));
        header.set("Content-Disposition", "inline; filename=" + filename.toString());
        header.setContentLength(Long.valueOf(properties.getProperty("length")));
        InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
        return ResponseEntity.ok().headers(header).body(isr);
    } catch (FileNotFoundException e) {
        log.error("FileNotFoundException: ", e.getMessage());
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}
Example 7
Project: ignite-master  File: IgniteSpringHelperImpl.java View source code
/**
     * @param stream Input stream containing Spring XML configuration.
     * @return Context.
     * @throws IgniteCheckedException In case of error.
     */
private ApplicationContext initContext(InputStream stream) throws IgniteCheckedException {
    GenericApplicationContext springCtx;
    try {
        springCtx = new GenericApplicationContext();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(springCtx);
        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
        reader.loadBeanDefinitions(new InputStreamResource(stream));
        springCtx.refresh();
    } catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context " + "(make sure all classes used in Spring configuration are present at CLASSPATH) ", e);
        else
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context" + ", err=" + e.getMessage() + ']', e);
    }
    return springCtx;
}
Example 8
Project: jiva-master  File: SpringWorkflowModelStore.java View source code
public void addModel(InputStream is) {
    byte[] workflowAsString;
    try {
        workflowAsString = IOUtils.toByteArray(is);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    WorkflowModelImpl model = new WorkflowModelImpl();
    model.setXml(new String(workflowAsString));
    tlData.set(model);
    SpringApplicationContext ctx;
    try {
        ctx = (SpringApplicationContext) getContext(new InputStreamResource(new ByteArrayInputStream(workflowAsString)).getInputStream(), model);
    } catch (Exception e) {
        throw new RuntimeException("could not load workflow", e);
    }
    model.setApplicationContext(ctx);
    this.models.put(model.getName(), model);
}
Example 9
Project: opennms_dashboard-master  File: PropertiesGraphDao.java View source code
/**
     * <p>
     * loadProperties
     * </p>
     * Used exclusively by test code. Will ignore an "include.directory"
     * because we don't have a resource/path to do any useful "relative"
     * pathing to. Also anything loaded in this fashion will *not* have auto
     * reloading on changes, because there's no underlying Resource/File to
     * check against. Like, duh!
     * 
     * @param type
     *            a {@link java.lang.String} object.
     * @param in
     *            a {@link java.io.InputStream} object.
     * @throws java.io.IOException
     *             if any.
     */
public void loadProperties(String type, InputStream in) throws IOException {
    Resource resource = new InputStreamResource(in);
    // Not reloadable; we don't have a file to check for modifications
    PrefabGraphTypeDao t = createPrefabGraphType(type, resource, false);
    if (t != null) {
        m_types.put(t.getName(), new FileReloadContainer<PrefabGraphTypeDao>(t));
    }
}
Example 10
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 11
Project: spring-cloud-netflix-master  File: RequestContentDataExtractor.java View source code
private static MultiValueMap<String, Object> extractFromMultipartRequest(MultipartHttpServletRequest request) throws IOException {
    MultiValueMap<String, Object> builder = new LinkedMultiValueMap<>();
    Set<String> queryParams = findQueryParams(request);
    for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
        String key = entry.getKey();
        if (!queryParams.contains(key)) {
            for (String value : entry.getValue()) {
                HttpHeaders headers = new HttpHeaders();
                String type = request.getMultipartContentType(key);
                if (type != null) {
                    headers.setContentType(MediaType.valueOf(type));
                }
                builder.add(key, new HttpEntity<>(value, headers));
            }
        }
    }
    for (Entry<String, List<MultipartFile>> parts : request.getMultiFileMap().entrySet()) {
        for (MultipartFile file : parts.getValue()) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData(file.getName(), file.getOriginalFilename());
            if (file.getContentType() != null) {
                headers.setContentType(MediaType.valueOf(file.getContentType()));
            }
            HttpEntity entity = new HttpEntity<>(new InputStreamResource(file.getInputStream()), headers);
            builder.add(parts.getKey(), entity);
        }
    }
    return builder;
}
Example 12
Project: spring-framework-master  File: HttpRange.java View source code
/**
	 * Turn a {@code Resource} into a {@link ResourceRegion} using the range
	 * information contained in the current {@code HttpRange}.
	 * @param resource the {@code Resource} to select the region from
	 * @return the selected region of the given {@code Resource}
	 * @since 4.3
	 */
public ResourceRegion toResourceRegion(Resource resource) {
    // Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
    // Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
    Assert.isTrue(resource.getClass() != InputStreamResource.class, "Cannot convert an InputStreamResource to a ResourceRegion");
    try {
        long contentLength = resource.contentLength();
        Assert.isTrue(contentLength > 0, "Resource content length should be > 0");
        long start = getRangeStart(contentLength);
        long end = getRangeEnd(contentLength);
        return new ResourceRegion(resource, start, end - start + 1);
    } catch (IOException ex) {
        throw new IllegalArgumentException("Failed to convert Resource to ResourceRegion", ex);
    }
}
Example 13
Project: spring-integration-master  File: InnerDefinitionHandlerAwareEndpointParserTests.java View source code
private ApplicationContext bootStrap(String configProperty) {
    ByteArrayInputStream stream = new ByteArrayInputStream(configProperty.getBytes());
    GenericApplicationContext ac = new GenericApplicationContext();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ac);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    reader.loadBeanDefinitions(new InputStreamResource(stream));
    ac.refresh();
    return ac;
}
Example 14
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 15
Project: Activiti-master  File: ProcessEngineMvcEndpoint.java View source code
/**
     * Look up the process definition by key. For example,
     * this is <A href="http://localhost:8080/activiti/processes/fulfillmentProcess">process-diagram for</A>
     * a process definition named {@code fulfillmentProcess}.
     */
@RequestMapping(value = "/processes/{processDefinitionKey:.*}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public ResponseEntity processDefinitionDiagram(@PathVariable String processDefinitionKey) {
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).latestVersion().singleResult();
    if (processDefinition == null) {
        return ResponseEntity.status(NOT_FOUND).body(null);
    }
    ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
    BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
    if (bpmnModel.getLocationMap().size() == 0) {
        BpmnAutoLayout autoLayout = new BpmnAutoLayout(bpmnModel);
        autoLayout.execute();
    }
    InputStream is = processDiagramGenerator.generateJpgDiagram(bpmnModel);
    return ResponseEntity.ok(new InputStreamResource(is));
}
Example 16
Project: jetstream-master  File: DataValidators.java View source code
@Override
public void validate(final String name, final Object value) throws IllegalArgumentException {
    String beanDefinition = (String) value;
    try {
        InputStream input = new ByteArrayInputStream(beanDefinition.getBytes());
        DefaultListableBeanFactory beans = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beans);
        reader.setValidating(true);
        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
        reader.loadBeanDefinitions(new InputStreamResource(input));
        validateBeanId(beanDefinition);
    } catch (Exception ex) {
        throw new IllegalArgumentException(String.format("%s is not valid :%s", name, ex.getMessage()));
    }
}
Example 17
Project: spring-a-gram-master  File: ApplicationController.java View source code
@RequestMapping(method = RequestMethod.GET, value = "/files/{filename}")
public ResponseEntity<?> getFile(@PathVariable String filename) {
    GridFsResource file = this.fileService.findOne(filename);
    if (file == null) {
        return ResponseEntity.notFound().build();
    }
    try {
        return ResponseEntity.ok().contentLength(file.contentLength()).contentType(MediaType.parseMediaType(file.getContentType())).body(new InputStreamResource(file.getInputStream()));
    } catch (IOException e) {
        return ResponseEntity.badRequest().body("Couldn't process the request");
    }
}
Example 18
Project: Yarrn-master  File: PhotoUploadRequest.java View source code
@Override
public String loadDataFromNetwork() throws Exception {
    final OAuthRequest request = new OAuthRequest(Verb.POST, application.getString(R.string.ravelry_url) + "/upload/request_token.json");
    Response requestTokenResponse = executeRequest(request);
    final String token = new JSONObject(requestTokenResponse.getBody()).getString("upload_token");
    try {
        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
        parts.add("upload_token", token);
        parts.add("access_key", application.getString(R.string.api_key));
        final InputStream inputStream = application.getContentResolver().openInputStream(photoUri);
        parts.add("file0", new InputStreamResource(inputStream) {

            @Override
            public long contentLength() throws IOException {
                return inputStream.available();
            }

            @Override
            public String getFilename() throws IllegalStateException {
                return photoUri.getLastPathSegment();
            }
        });
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Type", "multipart/form-data");
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(parts, headers);
        RestTemplate restTemplate = getRestTemplate();
        restTemplate.getMessageConverters().add(0, new FormHttpMessageConverter());
        UploadResult uploadResult = restTemplate.postForObject(application.getString(R.string.ravelry_url) + "/upload/image.json", requestEntity, UploadResult.class);
        Integer imageId = uploadResult.get("uploads").get("file0").get("image_id");
        return addPhotoToProject(imageId, projectId);
    } catch (final FileNotFoundException e) {
        onError(e);
        throw e;
    }
}
Example 19
Project: yum-repo-server-master  File: FileController.java View source code
@RequestMapping(value = "/{repo}/{arch}/{filename:.+}", method = GET)
public ResponseEntity<InputStreamResource> deliverFile(@PathVariable("repo") String repo, @PathVariable("arch") String arch, @PathVariable("filename") String filename) throws IOException {
    BoundedGridFsResource resource = fileStorageService.getResource(new FileDescriptor(repo, arch, filename));
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentLength(resource.contentLength());
    InApplicationMonitor.getInstance().incrementCounter(getClass().getName() + ".get.rpm");
    return new ResponseEntity<>(resource, withContentHeaders(httpHeaders, resource), OK);
}
Example 20
Project: axis2-java-master  File: ApplicationContextUtil.java View source code
/**
     * Method to get the spring application context for a spring service. This
     * method will first check the META-INF(or meta-inf) directory for the
     * '<service-name>-application-context.xml file. If the file is not found
     * then it will check whether file path is set as a parameter in
     * service.xml. If the context file is set as a parameter for a service
     * group, then the context will be add to the group or else it will be add
     * to the service.
     * 
     * @param axisService
     * @return GenericApplicationContext
     * @throws AxisFault
     */
public static GenericApplicationContext getSpringApplicationContext(AxisService axisService) throws AxisFault {
    GenericApplicationContext appContext;
    Parameter appContextParameter = axisService.getParameter(SPRING_APPLICATION_CONTEXT);
    Parameter contextLocationParam = axisService.getParameter(SPRING_APPLICATION_CONTEXT_LOCATION);
    // return the application context
    if (appContextParameter != null) {
        appContext = (GenericApplicationContext) appContextParameter.getValue();
    // if the context is not found initialize a new one
    } else {
        appContext = new GenericApplicationContext();
        ClassLoader serviceCL = axisService.getClassLoader();
        appContext.setClassLoader(serviceCL);
        ClassLoader currentCL = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(serviceCL);
            XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext);
            // load the bean context file from the parameter
            if (contextLocationParam != null) {
                xbdr.loadBeanDefinitions(new ClassPathResource((String) contextLocationParam.getValue()));
                appContext.refresh();
                AxisServiceGroup axisServiceGroup = axisService.getAxisServiceGroup();
                Parameter springGroupCtxLocation = axisServiceGroup.getParameter(SPRING_APPLICATION_CONTEXT_LOCATION);
                // service
                if (springGroupCtxLocation != null) {
                    axisServiceGroup.addParameter(new Parameter(SPRING_APPLICATION_CONTEXT, appContext));
                } else {
                    axisService.addParameter(new Parameter(SPRING_APPLICATION_CONTEXT, appContext));
                }
                return appContext;
            }
            InputStream ctxFileInputStream = serviceCL.getResourceAsStream(DeploymentConstants.META_INF + File.separator + axisService.getName() + "-application-context.xml");
            // try for meta-inf
            if (ctxFileInputStream == null) {
                ctxFileInputStream = serviceCL.getResourceAsStream(DeploymentConstants.META_INF.toLowerCase() + File.separator + axisService.getName() + "-application-context.xml");
            }
            // load the context file from meta-inf
            if (ctxFileInputStream != null) {
                xbdr.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
                xbdr.loadBeanDefinitions(new InputStreamResource(ctxFileInputStream));
                appContext.refresh();
                axisService.addParameter(new Parameter(SPRING_APPLICATION_CONTEXT, appContext));
                return appContext;
            } else {
                throw new AxisFault("Spring context file cannot be located for AxisService");
            }
        } catch (Exception e) {
            throw AxisFault.makeFault(e);
        } finally {
            // restore the class loader
            Thread.currentThread().setContextClassLoader(currentCL);
        }
    }
    return appContext;
}
Example 21
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 22
Project: lilyproject-master  File: ModuleBuilder.java View source code
private Module buildInt(ModuleConfig cfg, ClassLoader classLoader, LilyRuntime runtime) throws ArtifactNotFoundException, MalformedURLException {
    infolog.info("Starting module " + cfg.getId() + " - " + cfg.getLocation());
    ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(classLoader);
        GenericApplicationContext applicationContext = new GenericApplicationContext();
        applicationContext.setDisplayName(cfg.getId());
        applicationContext.setClassLoader(classLoader);
        // Note: before loading any beans in the spring container:
        //   * the spring build context needs access to the module, for possible injection & module-protocol resolving during bean initialization
        //   * the module also needs to have the reference to the applicationcontext, as there might be beans trying to get while initializing
        ModuleImpl module = new ModuleImpl(classLoader, applicationContext, cfg.getDefinition(), cfg.getModuleSource());
        SpringBuildContext springBuildContext = new SpringBuildContext(runtime, module, classLoader);
        SPRING_BUILD_CONTEXT.set(springBuildContext);
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
        xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
        xmlReader.setBeanClassLoader(classLoader);
        for (ModuleSource.SpringConfigEntry entry : cfg.getModuleSource().getSpringConfigs(runtime.getMode())) {
            InputStream is = entry.getStream();
            try {
                xmlReader.loadBeanDefinitions(new InputStreamResource(is, entry.getLocation() + " in " + cfg.getDefinition().getFile().getAbsolutePath()));
            } finally {
                IOUtils.closeQuietly(is, entry.getLocation());
            }
        }
        applicationContext.refresh();
        // Handle the service exports
        for (SpringBuildContext.JavaServiceExport entry : springBuildContext.getExportedJavaServices()) {
            Class serviceType = entry.serviceType;
            if (!serviceType.isInterface()) {
                throw new LilyRTException("Exported service is not an interface: " + serviceType.getName());
            }
            String beanName = entry.beanName;
            Object component;
            try {
                component = applicationContext.getBean(beanName);
            } catch (NoSuchBeanDefinitionException e) {
                throw new LilyRTException("Bean not found for service to export, service type " + serviceType.getName() + ", bean name " + beanName, e);
            }
            if (!serviceType.isAssignableFrom(component.getClass())) {
                throw new LilyRTException("Exported service does not implemented specified type interface. Bean = " + beanName + ", interface = " + serviceType.getName());
            }
            infolog.debug(" exporting bean " + beanName + " for service " + serviceType.getName());
            Object service = shieldJavaService(serviceType, component, module, classLoader);
            runtime.getJavaServiceManager().addService(serviceType, cfg.getId(), entry.name, service);
        }
        module.start();
        return module;
    } catch (Throwable e) {
        throw new LilyRTException("Error constructing module defined at " + cfg.getDefinition().getFile().getAbsolutePath(), e);
    } finally {
        Thread.currentThread().setContextClassLoader(previousContextClassLoader);
        SPRING_BUILD_CONTEXT.set(null);
    }
}
Example 23
Project: qcadoo-master  File: ModelXmlToHbmConverterImpl.java View source code
@Override
public Resource[] convert(final Resource... resources) {
    List<Resource> hbms = new ArrayList<Resource>();
    for (Resource resource : resources) {
        if (resource.isReadable()) {
            LOG.info("Converting " + resource + " to hbm.xml");
            byte[] hbm = getHbm(resource);
            if (LOG.isDebugEnabled()) {
                LOG.debug(new String(hbm));
            }
            hbms.add(new InputStreamResource(new ByteArrayInputStream(hbm)));
        }
    }
    return hbms.toArray(new Resource[hbms.size()]);
}
Example 24
Project: riptide-master  File: StreamsTest.java View source code
@Test
public void shouldNotCallConsumerForEmptyStream() {
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(0);
    server.expect(requestTo(url)).andRespond(withSuccess().headers(headers).body(new InputStreamResource(new ByteArrayInputStream(new byte[0]))).contentType(APPLICATION_X_JSON_STREAM));
    @SuppressWarnings("unchecked") final ThrowingConsumer<AccountBody, Exception> verifier = mock(ThrowingConsumer.class);
    unit.get("/accounts").dispatch(status(), on(OK).call(streamOf(AccountBody.class), forEach(verifier)), anyStatus().call(this::fail)).join();
    verifyZeroInteractions(verifier);
}
Example 25
Project: spring-batch-examples-readers-master  File: ZipMultiResourceItemReader.java View source code
/**
     * Extract only files from the zip archive.
     *
     * @param currentZipFile
     * @param extractedResources
     * @throws IOException 
     */
private static void extractFiles(final ZipFile currentZipFile, final List<Resource> extractedResources) throws IOException {
    Enumeration<? extends ZipEntry> zipEntryEnum = currentZipFile.entries();
    while (zipEntryEnum.hasMoreElements()) {
        ZipEntry zipEntry = zipEntryEnum.nextElement();
        LOG.info("extracting:" + zipEntry.getName());
        // traverse directories
        if (!zipEntry.isDirectory()) {
            // add inputStream
            extractedResources.add(new InputStreamResource(currentZipFile.getInputStream(zipEntry), zipEntry.getName()));
            LOG.info("using extracted file:" + zipEntry.getName());
        }
    }
}
Example 26
Project: spring-cloud-stream-master  File: BinderConfigurationParsingTests.java View source code
@Test
public void testParseOneBinderConfiguration() throws Exception {
    // this is just checking that resources are passed and classes are loaded properly
    // class values used here are not binder configurations
    String oneBinderConfiguration = "binder1=org.springframework.cloud.stream.binder.stub1.StubBinder1Configuration";
    Resource resource = new InputStreamResource(new ByteArrayInputStream(oneBinderConfiguration.getBytes()));
    Collection<BinderType> binderConfigurations = BinderFactoryConfiguration.parseBinderConfigurations(classLoader, resource);
    Assert.assertNotNull(binderConfigurations);
    Assert.assertThat(binderConfigurations.size(), equalTo(1));
    Assert.assertThat(binderConfigurations, contains(both(hasProperty("defaultName", equalTo("binder1"))).and(hasProperty("configurationClasses", hasItemInArray(StubBinder1Configuration.class)))));
}
Example 27
Project: spring-framework-2.5.x-master  File: XmlBeanDefinitionReaderTests.java View source code
public void testWithOpenInputStream() {
    try {
        SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
        ;
        Resource resource = new InputStreamResource(getClass().getResourceAsStream("test.xml"));
        new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource);
        fail("Should have thrown BeanDefinitionStoreException (can't determine validation mode)");
    } catch (BeanDefinitionStoreException expected) {
    }
}
Example 28
Project: wso2-synapse-master  File: SpringMediator.java View source code
private synchronized void buildAppContext(MessageContext synCtx, SynapseLog synLog) {
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Creating Spring ApplicationContext from key : " + configKey);
    }
    GenericApplicationContext appContext = new GenericApplicationContext();
    XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext);
    xbdr.setValidating(false);
    Object springConfig = synCtx.getEntry(configKey);
    if (springConfig == null) {
        String errorMessage = "Cannot look up Spring configuration " + configKey;
        log.error(errorMessage);
        //throw new SynapseException(errorMessage);
        return;
    }
    xbdr.loadBeanDefinitions(new InputStreamResource(SynapseConfigUtils.getStreamSource(springConfig).getInputStream()));
    appContext.refresh();
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Spring ApplicationContext from key : " + configKey + " created");
    }
    this.appContext = appContext;
}
Example 29
Project: xillium-master  File: ServicePlatform.java View source code
@SuppressWarnings("unchecked")
private ApplicationContext load(ApplicationContext parent, ServiceModule module, InputStream stream, ServiceModuleInfo info) {
    GenericApplicationContext gac = new GenericApplicationContext(parent);
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(gac);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    reader.loadBeanDefinitions(new InputStreamResource(stream));
    gac.refresh();
    gac.start();
    _logger.config("Loading service modules from ApplicationContext " + gac.getId());
    // looking for a local Persistence bean and storing it in info.persistence.second; falling back to the root Persistence bean
    if (gac.containsLocalBean(PERSISTENCE)) {
        _persistences.put(module.simple, info.persistence.second = (Persistence) gac.getBean(PERSISTENCE));
    } else {
        info.persistence.second = info.persistence.first;
    }
    for (String id : gac.getBeanNamesForType(Service.class)) {
        String fullname = module.simple + '/' + id;
        try {
            Class<? extends DataObject> request = ((DynamicService) gac.getBean(id)).getRequestType();
            _logger.config("Service '" + fullname + "' request description captured: " + request.getName());
            info.descriptions.put(fullname, "json:" + DataObject.Util.describe((Class<? extends DataObject>) request));
        } catch (ClassCastException x) {
            try {
                Class<?> request = Class.forName(gac.getBeanDefinition(id).getBeanClassName() + "$Request");
                if (DataObject.class.isAssignableFrom(request)) {
                    _logger.config("Service '" + fullname + "' request description captured: " + request.getName());
                    info.descriptions.put(fullname, "json:" + DataObject.Util.describe((Class<? extends DataObject>) request));
                } else {
                    _logger.warning("Service '" + fullname + "' defines a Request type that is not a DataObject");
                    info.descriptions.put(fullname, "json:{}");
                }
            } catch (Exception t) {
                _logger.config("Service '" + fullname + "' does not expose its request structure");
                info.descriptions.put(fullname, "json:{}");
            }
        }
        _logger.config("Service '" + fullname + "' class=" + gac.getBean(id).getClass().getName());
        _registry.put(fullname, new Pair<Service, Persistence>((Service) gac.getBean(id), info.persistence.second));
    }
    for (String id : gac.getBeanNamesForType(ServiceAugmentation.class)) {
        info.augmentations.add(gac.getBean(id, ServiceAugmentation.class).name(module.simple));
    }
    for (String id : gac.getBeanNamesForType(PlatformAware.class)) {
        info.plcas.add(new Pair<String, PlatformAware>(module.simple, (PlatformAware) gac.getBean(id)));
    }
    // Manageable object registration: objects are registered under "type=class-name,name=context-path/module-name/bean-id"
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    for (String id : gac.getBeanNamesForType(Manageable.class)) {
        try {
            Manageable manageable = (Manageable) gac.getBean(id);
            info.attrs.put("type", manageable.getClass().getSimpleName());
            info.attrs.put("name", _application + '/' + module.name + '/' + id);
            ObjectName name = new ObjectName(module.domain, info.attrs);
            manageable.assignObjectName(name);
            _logger.config("Registering MBean '" + id + "' as " + name);
            mbs.registerMBean(manageable, name);
            _manageables.push(name);
        } catch (Exception x) {
            _logger.log(Level.WARNING, "MBean '" + id + "' failed to register", x);
        }
    }
    _logger.config("Done with service modules in ApplicationContext " + gac.getId());
    return gac;
}
Example 30
Project: cagrid2-master  File: ApplicationServiceProvider.java View source code
@SuppressWarnings("unchecked")
private static ApplicationContext getApplicationContext(ApplicationContext ctx, String service, String url, Boolean secured) throws Exception {
    if (service == null || service.trim().length() == 0)
        throw new Exception("Name of the service can not be empty");
    Map<String, Object> serviceInfoMap = (Map<String, Object>) ctx.getBean(service);
    if (serviceInfoMap == null)
        throw new Exception("Change the configuration file!!!");
    //Initialized instances found in the configuration
    String asName = (String) serviceInfoMap.get("APPLICATION_SERVICE_BEAN");
    ApplicationService as = (ApplicationService) ctx.getBean(asName);
    AuthenticationProvider ap = (AuthenticationProvider) serviceInfoMap.get("AUTHENTICATION_SERVICE_BEAN");
    //Returning initialized instance
    if (//Empty URL, return the service. This helps in improving performance
    (!secured && as != null && url == null) || (secured && as != null && ap != null && url == null))
        return ctx;
    String serviceInfo = (String) serviceInfoMap.get("APPLICATION_SERVICE_CONFIG");
    ;
    if (url == null)
        url = (String) serviceInfoMap.get("APPLICATION_SERVICE_URL");
    //URL_KEY must be present if the user is trying to use the url to reach the service
    if (serviceInfo == null || (url == null && serviceInfo.indexOf("URL_KEY") > 0) || (url != null && serviceInfo.indexOf("URL_KEY") < 0))
        throw new Exception("Change the configuration file!!!");
    //Resetting the URL as URL_KEY is absent in the configuration
    if (serviceInfo.indexOf("URL_KEY") < 0 || url == null)
        url = "";
    serviceInfo = serviceInfo.replace("URL_KEY", url);
    //Prepare in memory configuration from the information retrieved of the configuration file
    String xmlFileString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\"><beans>" + serviceInfo + "</beans>";
    GenericApplicationContext context = new GenericApplicationContext();
    context.setClassLoader(ApplicationServiceProvider.class.getClassLoader());
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
    InputStreamResource inputStreamResource = new InputStreamResource(new ByteArrayInputStream(xmlFileString.getBytes()));
    xmlReader.loadBeanDefinitions(inputStreamResource);
    context.refresh();
    as = (ApplicationService) context.getBean("applicationService");
    ap = (AuthenticationProvider) context.getBean("authenticationProvider");
    //Make sure the configuration has the required objects present
    if (as == null || (secured && ap == null))
        throw new Exception("Change the configuration file!!!");
    return context;
}
Example 31
Project: crowdsource-master  File: ProjectController.java View source code
@Secured({ Roles.ROLE_TRUSTED_ANONYMOUS, Roles.ROLE_USER })
@RequestMapping(value = "/projects/{projectId}/attachments/{fileReference}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> serveProjectAttachment(@PathVariable("projectId") String projectId, @PathVariable("fileReference") String fileReference) throws IOException {
    final Attachment attachment = projectService.loadProjectAttachment(projectId, Attachment.asLookupByIdCommand(fileReference));
    return ResponseEntity.ok().contentLength(attachment.getSize()).contentType(MediaType.valueOf(attachment.getType())).body(new InputStreamResource(attachment.getPayload()));
}
Example 32
Project: stormpath-sdk-java-master  File: ConfigJwkFactory.java View source code
@Override
public JwkResult apply(JwkConfig jwk) {
    SignatureAlgorithm signatureAlgorithm = null;
    String kid = jwk.getId();
    Key key = null;
    String value = jwk.getAlg();
    if (value != null) {
        try {
            signatureAlgorithm = SignatureAlgorithm.forName(value);
        } catch (SignatureException e) {
            String msg = "Unsupported stormpath.zuul.account.header.jwt.key.alg value: " + value + ".  " + "Please use only " + SignatureAlgorithm.class.getName() + " enum names: " + Strings.arrayToCommaDelimitedString(SignatureAlgorithm.values()).replace("NONE,", "");
            throw new IllegalArgumentException(msg, e);
        }
    }
    byte[] bytes = null;
    Resource keyResource = jwk.getResource();
    String keyString = jwk.getValue();
    boolean keyStringSpecified = Strings.hasText(keyString);
    if (keyResource != null && keyStringSpecified) {
        String msg = "Both the stormpath.zuul.account.header.jwt.key.value and " + "stormpath.zuul.account.header.jwt.key.resource properties may not be set simultaneously.  " + "Please choose one.";
        throw new IllegalArgumentException(msg);
    }
    if (keyStringSpecified) {
        String encoding = jwk.getEncoding();
        if (keyString.startsWith(PemResourceKeyResolver.PEM_PREFIX)) {
            encoding = "pem";
        }
        if (encoding == null) {
            //default to the JWK specification format:
            encoding = "base64url";
        }
        if (encoding.equalsIgnoreCase("base64url")) {
            bytes = TextCodec.BASE64URL.decode(keyString);
        } else if (encoding.equalsIgnoreCase("base64")) {
            bytes = TextCodec.BASE64.decode(keyString);
        } else if (encoding.equalsIgnoreCase("utf8")) {
            bytes = keyString.getBytes(StandardCharsets.UTF_8);
        } else if (encoding.equalsIgnoreCase("pem")) {
            byte[] resourceBytes = keyString.getBytes(StandardCharsets.UTF_8);
            ByteArrayInputStream bais = new ByteArrayInputStream(resourceBytes);
            String description = "stormpath.zuul.account.header.jwt.key.value";
            keyResource = new InputStreamResource(bais, description);
        } else {
            throw new IllegalArgumentException("Unsupported encoding '" + encoding + "'.  Supported " + "encodings: base64url, base64, utf8, pem.");
        }
    }
    if (bytes != null && bytes.length > 0) {
        if (signatureAlgorithm == null) {
            //choose the best available alg based on available key:
            signatureAlgorithm = getAlgorithm(bytes);
        }
        if (!signatureAlgorithm.isHmac()) {
            String algName = signatureAlgorithm.name();
            String msg = "It appears that the stormpath.zuul.account.header.jwt.key.value " + "is a shared (symmetric) secret key, and this requires the " + "stormpath.zuul.account.header.jwt.key.alg value to equal HS256, HS384, or HS512. " + "The specified stormpath.zuul.account.header.jwt.key.alg value is " + algName + ". " + "If you wish to use the " + algName + " algorithm, please ensure that either 1) " + "stormpath.zuul.account.header.jwt.key.value is a private asymmetric PEM-encoded string, " + "or 2) set the stormpath.zuul.account.header.jwt.key.resource property to a Spring " + "Resource path where the PEM-encoded key file resides, or " + "or 3) define a bean named 'stormpathForwardedAccountJwtSigningKey' that returns an " + signatureAlgorithm.getFamilyName() + " private key instance.";
            throw new IllegalArgumentException(msg);
        }
        key = new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
    }
    if (keyResource != null) {
        Function<Resource, Key> resourceKeyResolver = createResourceKeyFunction(keyResource, keyStringSpecified);
        Assert.notNull(resourceKeyResolver, "resourceKeyResolver instance cannot be null.");
        key = resourceKeyResolver.apply(keyResource);
        if (key == null) {
            String msg = "Resource to Key resolver/function did not return a key for specified resource [" + keyResource + "].  If providing your own implementation of this function, ensure it does not " + "return null.";
            throw new IllegalStateException(msg);
        }
        Assert.notNull(key, "ResourceKeyResolver function did not return a key for specified resource [" + keyResource + "]");
        if (signatureAlgorithm == null) {
            if (key instanceof RSAKey) {
                signatureAlgorithm = SignatureAlgorithm.RS256;
            } else if (key instanceof ECKey) {
                signatureAlgorithm = SignatureAlgorithm.ES256;
            } else {
                String msg = "Unable to detect jwt signing key type to provide a default signature " + "algorithm.  Please specify the stormpath.zuul.account.header.jwt.key.alg property.";
                throw new IllegalArgumentException(msg);
            }
        }
        if (key instanceof RSAKey && !signatureAlgorithm.getFamilyName().equalsIgnoreCase("RSA")) {
            String msg = "Signature algorithm [" + signatureAlgorithm + "] is not " + "compatible with the specified RSA key.";
            throw new IllegalArgumentException(msg);
        }
        if (key instanceof ECKey && !signatureAlgorithm.getFamilyName().equalsIgnoreCase("Elliptic Curve")) {
            String msg = "Signature algorithm [" + signatureAlgorithm + "] is not " + "compatible with the specified Elliptic Curve key.";
            throw new IllegalArgumentException(msg);
        }
        Assert.isTrue(key instanceof PrivateKey, "Specified asymmetric signing key is not a PrivateKey.  " + "Please ensure you specify a private (not public) key.");
    }
    if (key == null) {
        //fall back to the default key as the signing key
        return defaultKeyFunction.apply(signatureAlgorithm);
    }
    return new DefaultJwkResult(signatureAlgorithm, key, kid);
}
Example 33
Project: summerb-master  File: ArticleController.java View source code
@RequestMapping(method = RequestMethod.GET, value = "/articles-attachments/{id}/{proposedName}")
public ResponseEntity<InputStreamResource> getAttachment(Model model, @PathVariable("id") long id, HttpServletResponse response) throws AttachmentNotFoundException {
    try {
        Attachment attachment = attachmentService.findById(id);
        if (attachment == null) {
            throw new AttachmentNotFoundException(id);
        }
        long now = new Date().getTime();
        HttpHeaders headers = new HttpHeaders();
        headers.setCacheControl("private");
        headers.setExpires(now + DAY);
        headers.setContentType(MediaType.parseMediaType(mimeTypeResolver.resolveContentTypeByFileName(attachment.getName())));
        headers.setContentLength((int) attachment.getSize());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + attachment.getName() + "\"");
        // NOTE: Looks like there is a bug in the spring - it will add
        // Last-Modified twice to the response
        // responseHeaders.setLastModified(maxLastModified);
        response.setDateHeader("Last-Modified", now);
        InputStreamResource ret = new InputStreamResource(articleService.getAttachmnetContent(id));
        return new ResponseEntity<InputStreamResource>(ret, headers, HttpStatus.OK);
    } catch (AttachmentNotFoundException t) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setHeader("Error", "File not found");
        return null;
    } catch (Throwable t) {
        log.warn("Failed to get article attachment", t);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setHeader("Error", "Failed to get article attachment -> " + ErrorUtils.getAllMessages(t));
        return null;
    }
}
Example 34
Project: common_utils-master  File: EmailService.java View source code
/**
     * 处�附件
     *
     * @param emailVo
     * @param msgHelper
     * @throws javax.mail.MessagingException
     */
private void handlerAttachments(EmailVo emailVo, MimeMessageHelper msgHelper) throws MessagingException {
    if (emailVo.getAttachmentVos() != null) {
        // 检查附件
        for (AttachmentVo attachmentVo : emailVo.getAttachmentVos()) {
            File attachment = attachmentVo.getAttachment();
            if (attachment == null) {
                InputStream inputStream = attachmentVo.getAttachmentInputStream();
                if (attachmentVo.getAttachmentName() == null) {
                    attachmentVo.setAttachmentName(new Date().toString());
                }
                InputStreamSource inputStreamSource = new InputStreamResource(inputStream);
                msgHelper.addAttachment(attachmentVo.getAttachmentName(), inputStreamSource);
            } else {
                if (attachmentVo.getAttachmentName() == null) {
                    attachmentVo.setAttachmentName(attachment.getName());
                }
                try {
                    msgHelper.addAttachment(MimeUtility.encodeWord(attachmentVo.getAttachmentName()), attachment);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Example 35
Project: strongbox-master  File: NugetPackageController.java View source code
@ApiOperation(value = "Used to download a package")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "The package was downloaded successfully."), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "An error occurred.") })
@PreAuthorize("hasAuthority('ARTIFACTS_RESOLVE')")
@RequestMapping(path = "{storageId}/{repositoryId}/download/{packageId}/{packageVersion}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM)
public ResponseEntity<?> getPackage(@ApiParam(value = "The storageId", required = true) @PathVariable(name = "storageId") String storageId, @ApiParam(value = "The repositoryId", required = true) @PathVariable(name = "repositoryId") String repositoryId, @ApiParam(value = "The packageId", required = true) @PathVariable(name = "packageId") String packageId, @ApiParam(value = "The packageVersion", required = true) @PathVariable(name = "packageVersion") String packageVersion) {
    Storage storage = configurationManager.getConfiguration().getStorage(storageId);
    Repository repository = storage.getRepository(repositoryId);
    if (!repository.isInService()) {
        logger.error("Repository is not in service...");
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build();
    }
    String path = String.format("%s/%s/%s.%s.nupkg", packageId, packageVersion, packageId, packageVersion);
    try {
        ArtifactInputStream is = (ArtifactInputStream) getArtifactManagementService().resolve(storageId, repositoryId, path);
        if (is == null) {
            return ResponseEntity.notFound().build();
        }
        try (TempNupkgFile nupkgFile = new TempNupkgFile(is)) {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Length", String.valueOf(nupkgFile.getSize()));
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", nupkgFile.getFileName()));
            ArtifactControllerHelper.setHeadersForChecksums(is, headers);
            return new ResponseEntity<Resource>(new InputStreamResource(nupkgFile.getStream()), headers, HttpStatus.OK);
        }
    } catch (Exception e) {
        logger.error(String.format("Failed to process Nuget get request: %s:%s:%s:%s", storageId, repositoryId, packageId, packageVersion), e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }
}
Example 36
Project: alien4cloud-master  File: EditorController.java View source code
/**
     * Download a temporary file which is not yet commited (uploaded or modified through an operation).
     *
     * @param topologyId The if of the topology.
     * @param artifactId The id of the temporary artifact.
     * @return The response entity with the input stream of the file.
     */
@ApiIgnore
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/{topologyId:.+}/file/{artifactId:.+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<InputStreamResource> downloadTempFile(@PathVariable String topologyId, @PathVariable String artifactId) {
    editorService.checkAuthorization(topologyId);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    long length = artifactRepository.getFileLength(artifactId);
    return ResponseEntity.ok().headers(headers).contentLength(length).contentType(MediaType.parseMediaType("application/octet-stream")).body(new InputStreamResource(artifactRepository.getFile(artifactId)));
}
Example 37
Project: entermedia-core-master  File: BaseWebServer.java View source code
public synchronized void initialize() {
    if (getRootDirectory() == null) {
        String path = System.getProperty("oe.root.path");
        if (path != null) {
            setRootDirectory(new File(path).getAbsoluteFile());
        }
    }
    if (getRootDirectory() == null) {
        throw new IllegalStateException("Root directory is not defined");
    }
    try {
        //			DefaultListableBeanFactory factory = new DefaultListableBeanFactory()
        //			{ 
        //				public boolean isFactoryBean(String name) throws org.springframework.beans.factory.NoSuchBeanDefinitionException 
        //				{
        //					String beanName = transformedBeanName(name);
        //
        //					Object beanInstance = getSingleton(beanName, false);
        //					if (beanInstance != null) {
        //						boolean ret = (beanInstance instanceof FactoryBean || beanInstance instanceof BeanPostProcessor);
        //						return ret;
        //					}
        //					else if (containsSingleton(beanName)) {
        //						// null instance registered
        //						return false;
        //					}
        //
        //					// No singleton instance found -> check bean definition.
        //					if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
        //						// No bean definition found in this factory -> delegate to parent.
        //						return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
        //					}
        //
        //					return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
        //				};
        //			};
        SpringContext context = new //factory
        SpringContext() {

            public org.springframework.core.io.Resource getResource(String location) {
                File custom = new File(getRootDirectory(), "/WEB-INF/src/" + location);
                if (custom.exists()) {
                    return new FileSystemResource(custom);
                }
                File folders = new File(getRootDirectory(), "/WEB-INF/base/");
                File[] children = folders.listFiles();
                if (children != null) {
                    for (int i = 0; i < children.length; i++) {
                        File script = new File(children[i], "/src/" + location);
                        if (script.exists()) {
                            return new FileSystemResource(script);
                        }
                    }
                }
                return super.getResource(location);
            }

            ;
        };
        context.setValidating(false);
        ScriptPathLoader pathloader = new ScriptPathLoader();
        pathloader.setRoot(getRootDirectory());
        List classpathfolders = pathloader.findPaths();
        GroovyScriptEngine engine = new GroovyScriptEngine((String[]) classpathfolders.toArray(new String[classpathfolders.size()]));
        ClassLoader loader = engine.getGroovyClassLoader();
        //			
        //			if( loader == null)
        //			{
        //				loader = ClassLoader.getSystemClassLoader();
        //			}
        context.setClassLoader(loader);
        //InputStreamResource resource = new InputStreamResource(loader.getResourceAsStream("entermedia.xml"));
        context.load(new UrlResource(loader.getResource("entermedia.xml")));
        context.getBeanFactory().registerSingleton("WebServer", this);
        context.getBeanFactory().registerSingleton("root", getRootDirectory());
        List sorted = getAllPlugIns();
        for (Iterator iter = sorted.iterator(); iter.hasNext(); ) {
            PlugIn plugin = (PlugIn) iter.next();
            log.info("Loading " + plugin.getPluginXml().getPath());
            context.load(new UrlResource(plugin.getPluginXml()));
        }
        //Loop over the src folders
        File folders = new File(getRootDirectory(), "/WEB-INF/base/");
        File[] children = folders.listFiles();
        if (children != null) {
            for (int i = 0; i < children.length; i++) {
                File script = new File(children[i], "/src/plugin.xml");
                if (script.exists()) {
                    context.load(new FileSystemResource(script));
                }
            }
        }
        File custom = new File(getRootDirectory(), "/WEB-INF/src/plugin.xml");
        if (custom.exists()) {
            context.load(new FileSystemResource(custom));
        }
        //TODO: Use a directory of files
        File overrideFile = new File(getRootDirectory(), "/WEB-INF/pluginoverrides.xml");
        if (overrideFile.exists()) {
            context.load(new FileSystemResource(overrideFile));
        }
        context.refresh();
        fieldBeanFactory = context;
    } catch (Throwable ex) {
        log.error("Could not start server: ", ex);
        throw new OpenEditRuntimeException(ex);
    }
    //		JarReader reader = new JarReader()  //This is for Windows since it locks files. Did not seem to fix the problem
    //		{
    //			//Call back
    //			public void processFile( File inFile)
    //			{
    //				loadPluginDefs( inFile );
    //			}
    //		};
    //		reader.processInClasspath("plugin.xml");
    //		File lib = new File( getRootDirectory(),"WEB-INF/lib");
    //		reader.processInLibDir(lib,"plugin.xml");
    //		overridePlugIns();
    Thread sh = new Thread(new //This is in case the JVM is shut down
    Runnable() {

        public void run() {
            try {
                getOpenEditEngine().shutdown();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
    });
    Runtime.getRuntime().addShutdownHook(sh);
    reloadMounts();
    try {
        Page page = getPageManager().getPage("/WEB-INF/startup.html");
        BaseWebPageRequest request = new BaseWebPageRequest();
        request.setContentPage(page);
        request.setPage(page);
        if (page.getPageSettings().exists()) {
            getOpenEditEngine().executePathActions(request);
        }
        if (getModuleManager().contains("PathEventModule")) {
            getModuleManager().execute("PathEventModule.init", request);
        }
    } catch (Throwable ex) {
        log.error("Could not initiallize cleanly ", ex);
    }
//getBeanFactory().preInstantiateSingletons();
}
Example 38
Project: gemini.blueprint-master  File: AbstractOnTheFlyBundleCreatorTests.java View source code
/**
	 * Determine imports for the given bundle. Based on the user settings, this
	 * method will consider only the the test hierarchy until the testing
	 * framework is found or all classes available inside the test bundle. <p/>
	 * Note that split packages are not supported.
	 * 
	 * @return
	 */
private String[] determineImports() {
    boolean useTestClassOnly = false;
    // no jar entry present, bail out.
    if (jarEntries == null || jarEntries.isEmpty()) {
        logger.debug("No test jar content detected, generating bundle imports from the test class");
        useTestClassOnly = true;
    } else if (createManifestOnlyFromTestClass()) {
        logger.info("Using the test class for generating bundle imports");
        useTestClassOnly = true;
    } else
        logger.info("Using all classes in the jar for the generation of bundle imports");
    // className, class resource
    Map entries;
    if (useTestClassOnly) {
        entries = new LinkedHashMap(4);
        // get current class (test class that bootstraps the OSGi infrastructure)
        Class<?> clazz = getClass();
        String clazzPackage = null;
        String endPackage = AbstractOnTheFlyBundleCreatorTests.class.getPackage().getName();
        do {
            // consider inner classes as well
            List classes = new ArrayList(4);
            classes.add(clazz);
            CollectionUtils.mergeArrayIntoCollection(clazz.getDeclaredClasses(), classes);
            for (Iterator iterator = classes.iterator(); iterator.hasNext(); ) {
                Class<?> classToInspect = (Class) iterator.next();
                Package pkg = classToInspect.getPackage();
                if (pkg != null) {
                    clazzPackage = pkg.getName();
                    String classFile = ClassUtils.getClassFileName(classToInspect);
                    entries.put(classToInspect.getName().replace('.', '/').concat(ClassUtils.CLASS_FILE_SUFFIX), new InputStreamResource(classToInspect.getResourceAsStream(classFile)));
                } else // handle default package
                {
                    logger.warn("Could not find package for class " + classToInspect + "; ignoring...");
                }
            }
            clazz = clazz.getSuperclass();
        } while (!endPackage.equals(clazzPackage));
    } else
        entries = jarEntries;
    return determineImportsFor(entries);
}
Example 39
Project: orchidae-master  File: PictureController.java View source code
/**
     * actual method retrieving the picture from disk. Requested picture is only returned if the current user is allowed
     * to view it
     * 
     * @param id identification of picture
     * @param type type of the picture eg _t for thumbnail etc.
     * @return ResponseEntity containing the resource to the picture or NOT_FOUND
     * @throws IOException
     */
private ResponseEntity<Resource> _getPicture(String id, String type) throws IOException {
    File picture = fileUtil.getFileHandle(id + type);
    if (picture.exists()) {
        return new ResponseEntity<>(new InputStreamResource(FileUtils.openInputStream(picture)), HttpStatus.OK);
    } else {
        LOG.debug("Could not find picture with id {}", id);
        // picture doesn't exist so return 404
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}
Example 40
Project: activiti-crystalball-master  File: BeansConfigurationHelper.java View source code
public static SimulationEngineConfiguration parseSimulationEngineConfigurationFromInputStream(InputStream inputStream, String beanName) {
    Resource springResource = new InputStreamResource(inputStream);
    return parseSimulationEngineConfiguration(springResource, beanName);
}
Example 41
Project: activiti-engine-ppi-master  File: BeansConfigurationHelper.java View source code
public static ProcessEngineConfiguration parseProcessEngineConfigurationFromInputStream(InputStream inputStream, String beanName) {
    Resource springResource = new InputStreamResource(inputStream);
    return parseProcessEngineConfiguration(springResource, beanName);
}
Example 42
Project: FiWare-Template-Handler-master  File: BeansConfigurationHelper.java View source code
public static ProcessEngineConfiguration parseProcessEngineConfigurationFromInputStream(InputStream inputStream, String beanName) {
    Resource springResource = new InputStreamResource(inputStream);
    return parseProcessEngineConfiguration(springResource, beanName);
}
Example 43
Project: jenkow-plugin-master  File: BeansConfigurationHelper.java View source code
public static ProcessEngineConfiguration parseProcessEngineConfigurationFromInputStream(InputStream inputStream, String beanName) {
    Resource springResource = new InputStreamResource(inputStream);
    return parseProcessEngineConfiguration(springResource, beanName);
}
Example 44
Project: xbpm5-master  File: BeansConfigurationHelper.java View source code
public static ProcessEngineConfiguration parseProcessEngineConfigurationFromInputStream(InputStream inputStream, String beanName) {
    Resource springResource = new InputStreamResource(inputStream);
    return parseProcessEngineConfiguration(springResource, beanName);
}
Example 45
Project: spring-android-master  File: ResourceHttpMessageConverter.java View source code
@Override
protected Long getContentLength(Resource resource, MediaType contentType) throws IOException {
    // Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
    return (InputStreamResource.class.equals(resource.getClass()) ? null : resource.contentLength());
}
Example 46
Project: droolsjbpm-master  File: AbstractDroolsSpringDMTest.java View source code
@Override
protected Resource getTestingFrameworkBundlesConfiguration() {
    return new InputStreamResource(AbstractDroolsSpringDMTest.class.getResourceAsStream(TEST_FRAMEWORK_BUNDLES_CONF_FILE));
}
Example 47
Project: jtheque-core-master  File: I18NResourceFactory.java View source code
/**
     * Construct a I18NResource from the path using the class (with the class loader) to load it.
     *
     * @param classz The class to get the class loader.
     * @param path   The resource path.
     *
     * @return The I18NResource corresponding to the given resource.
     */
public static I18NResource fromResource(Class<?> classz, String path) {
    Resource resource = new InputStreamResource(classz.getClassLoader().getResourceAsStream(path));
    return new I18NResourceImpl(path.substring(path.lastIndexOf('/')), resource);
}
Example 48
Project: eclipse-swordfish-master  File: TargetPlatformOsgiTestCase.java View source code
@Override
protected Resource getTestingFrameworkBundlesConfiguration() {
    try {
        return new InputStreamResource(TargetPlatformOsgiTestCase.class.getClassLoader().getResource("boot-bundles.properties").openStream());
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
Example 49
Project: javasousuo-master  File: ResourceTest.java View source code
@Test
public void testInputStreamResource() {
    ByteArrayInputStream bis = new ByteArrayInputStream("Hello World!".getBytes());
    Resource resource = new InputStreamResource(bis);
    if (resource.exists()) {
        dumpStream(resource);
    }
    Assert.assertEquals(true, resource.isOpen());
}
Example 50
Project: spring-boot-master  File: AbstractJsonMarshalTester.java View source code
/**
	 * Return {@link ObjectContent} from reading from the specified input stream.
	 * @param inputStream the source input stream
	 * @return the {@link ObjectContent}
	 * @throws IOException on read error
	 */
public ObjectContent<T> read(InputStream inputStream) throws IOException {
    verify();
    Assert.notNull(inputStream, "InputStream must not be null");
    return read(new InputStreamResource(inputStream));
}