Java 类org.springframework.util.MimeTypeUtils 实例源码
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testSendBinaryDataWithContentType() throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
SourceApplication.class, "--server.port=0",
"--spring.jmx.enabled=false",
"--spring.cloud.stream.bindings.output.contentType=image/jpeg")) {
MessageCollector collector = context.getBean(MessageCollector.class);
Source source = context.getBean(Source.class);
byte[] data = new byte[] { 0, 1, 2, 3 };
source.output().send(MessageBuilder.withPayload(data)
.build());
Message<byte[]> message = (Message<byte[]>) collector
.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.IMAGE_JPEG));
assertThat(message.getPayload()).isEqualTo(data);
}
}
项目:smarti
文件:ConversationWebservice.java
@ApiOperation(value = "update a conversation", response = Conversation.class)
@RequestMapping(value = "{id}", method = RequestMethod.PUT, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<?> updateConversation(
AuthContext authContext,
@PathVariable("id") ObjectId id,
@RequestBody Conversation conversation
) {
final Conversation storedC = authenticationService.assertConversation(authContext, id);
// make sure the id is the right one
conversation.setId(storedC.getId());
final Client client = authenticationService.assertClient(authContext, conversation.getOwner());
//TODO: check that the
// * the user is from the client the stored conversation as as owner
return ResponseEntity.ok(conversationService.update(client, conversation,true, null));
}
项目:smarti
文件:UserWebservice.java
@ApiOperation(value = "signup", notes = "create a new account", response = UserDetailsResponse.class)
@RequestMapping(value = "/auth/signup", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<UserDetailsResponse> signUp(@RequestBody Map<String, String> data) {
if (!securityConfigurationProperties.getMongo().isEnableSignup()) {
return ResponseEntity.badRequest().build();
}
// Public access
final String login = data.get("login"),
password = data.get("password"),
mail = data.get("email");
if ( StringUtils.isNoneBlank(login, password, mail) && emailValidator.isValid(mail)) {
return ResponseEntity.ok(UserDetailsResponse.wrap(accountService.createAccount(login, mail, password)));
} else {
return ResponseEntity.badRequest().build();
}
}
项目:spring4-understanding
文件:DefaultStompSessionTests.java
@Test
public void handleErrorFrameWithConversionException() throws Exception {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
accessor.setContentType(MimeTypeUtils.APPLICATION_JSON);
accessor.addNativeHeader("foo", "bar");
accessor.setLeaveMutable(true);
byte[] payload = "{'foo':'bar'}".getBytes(UTF_8);
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(this.sessionHandler.getPayloadType(stompHeaders)).thenReturn(Map.class);
this.session.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));
verify(this.sessionHandler).getPayloadType(stompHeaders);
verify(this.sessionHandler).handleException(same(this.session), same(StompCommand.ERROR),
eq(stompHeaders), same(payload), any(MessageConversionException.class));
verifyNoMoreInteractions(this.sessionHandler);
}
项目:spring4-understanding
文件:DefaultStompSessionTests.java
@Test
public void handleMessageFrame() throws Exception {
this.session.afterConnected(this.connection);
StompFrameHandler frameHandler = mock(StompFrameHandler.class);
String destination = "/topic/foo";
Subscription subscription = this.session.subscribe(destination, frameHandler);
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.MESSAGE);
accessor.setDestination(destination);
accessor.setSubscriptionId(subscription.getSubscriptionId());
accessor.setContentType(MimeTypeUtils.TEXT_PLAIN);
accessor.setMessageId("1");
accessor.setLeaveMutable(true);
String payload = "sample payload";
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(frameHandler.getPayloadType(stompHeaders)).thenReturn(String.class);
this.session.handleMessage(MessageBuilder.createMessage(payload.getBytes(UTF_8), accessor.getMessageHeaders()));
verify(frameHandler).getPayloadType(stompHeaders);
verify(frameHandler).handleFrame(stompHeaders, payload);
verifyNoMoreInteractions(frameHandler);
}
项目:spring4-understanding
文件:StompHeaderAccessorTests.java
@Test
public void toNativeHeadersMessageFrame() {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE);
headers.setSubscriptionId("s1");
headers.setDestination("/d");
headers.setContentType(MimeTypeUtils.APPLICATION_JSON);
headers.updateStompCommandAsServerMessage();
Map<String, List<String>> actual = headers.toNativeHeaderMap();
assertEquals(actual.toString(), 4, actual.size());
assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER).get(0));
assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0));
assertEquals("application/json", actual.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0));
assertNotNull("message-id was not created", actual.get(StompHeaderAccessor.STOMP_MESSAGE_ID_HEADER).get(0));
}
项目:spring4-understanding
文件:StompHeaderAccessorTests.java
@Test
public void getShortLogMessage() {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
accessor.setDestination("/foo");
accessor.setContentType(MimeTypeUtils.APPLICATION_JSON);
accessor.setSessionId("123");
String actual = accessor.getShortLogMessage("payload".getBytes(Charset.forName("UTF-8")));
assertEquals("SEND /foo session=123 application/json payload=payload", actual);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 80; i++) {
sb.append("a");
}
final String payload = sb.toString() + " > 80";
actual = accessor.getShortLogMessage(payload.getBytes(UTF_8));
assertEquals("SEND /foo session=123 application/json payload=" + sb + "...(truncated)", actual);
}
项目:spring4-understanding
文件:WebSocketStompClientTests.java
@Test
public void sendWebSocketBinary() throws Exception {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
accessor.setDestination("/b");
accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM);
byte[] payload = "payload".getBytes(UTF_8);
getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));
ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class);
verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture());
BinaryMessage binaryMessage = binaryMessageCaptor.getValue();
assertNotNull(binaryMessage);
assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0",
new String(binaryMessage.getPayload().array(), UTF_8));
}
项目:reactive-data
文件:SimpleHttpServerBean.java
@Override
public Response serve(IHTTPSession session) {
Method m = session.getMethod();
switch(m)
{
case GET:
return doGet(session);
case POST:
return doPost(session);
default:
return newFixedLengthResponse(Status.NOT_IMPLEMENTED, MimeTypeUtils.TEXT_PLAIN_VALUE,"HTTP "+m);
}
}
项目:haven-platform
文件:AppConfigService.java
public void read(String mimeType, InputStream is) throws IOException {
Assert.hasText(mimeType, "MimeType string is null or empty.");
Assert.notNull(is, "InputStream is null or empty.");
MimeType mimeTypeObj = MimeTypeUtils.parseMimeType(mimeType);
if(MimeTypeUtils.APPLICATION_JSON.equals(mimeTypeObj)) {
Assert.hasText(mimeType, "MimeType '" + mimeType + "' is not supported.");
}
AppConfigObject aco = objectMapper.readValue(is, AppConfigObject.class);
final String version = aco.getVersion();
if(!VERSION.equals(version)) {
throw new RuntimeException("Unsupported version of config: " + version);
}
ConfigReadContext ctx = new ConfigReadContext();
Map<String, Object> map = aco.getData();
Assert.notNull(map, "config has empty map");
for(Map.Entry<String, Object> oe : map.entrySet()) {
String name = oe.getKey();
ReConfigurableAdapter ca = adapters.get(name);
Assert.notNull(ca, "Can not find adapter with name: " + name);
Object value = oe.getValue();
Assert.notNull(value, "Config object is null for name: " + name);
ca.setConfig(ctx, value);
}
}
项目:haven-platform
文件:ConfigurationApi.java
@RequestMapping(path = "config", method = RequestMethod.GET)
public ResponseEntity<StreamingResponseBody> getConfig() {
HttpHeaders headers = new HttpHeaders();
// 'produces' in annotation does not work with stream
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"cluman_config.json\"");
return new ResponseEntity<>((os) -> {
appConfigService.write(MimeTypeUtils.APPLICATION_JSON_VALUE, os);
}, headers, HttpStatus.OK);
}
项目:dhis2-core
文件:DefaultPushAnalysisService.java
/**
* Uploads a byte array using FileResource and ExternalFileResource
*
* @param name name of the file to be stored
* @param bytes the byte array representing the file to be stored
* @return url pointing to the uploaded resource
* @throws IOException
*/
private String uploadImage( String name, byte[] bytes )
throws IOException
{
FileResource fileResource = new FileResource(
name,
MimeTypeUtils.IMAGE_PNG.toString(), // All files uploaded from PushAnalysis is PNG.
bytes.length,
ByteSource.wrap( bytes ).hash( Hashing.md5() ).toString(),
FileResourceDomain.PUSH_ANALYSIS
);
fileResourceService.saveFileResource( fileResource, bytes );
ExternalFileResource externalFileResource = new ExternalFileResource();
externalFileResource.setFileResource( fileResource );
externalFileResource.setExpires( null );
String accessToken = externalFileResourceService.saveExternalFileResource( externalFileResource );
return systemSettingManager.getInstanceBaseUrl() + "/api/externalFileResources/" + accessToken;
}
项目:janusz-backend
文件:KudosRestController.java
@RequestMapping(value = "/{kudosId}/plusOnes", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseMessage addNewPlusOne(@RequestBody @Valid NewPlusOneRequest newPlusOneRequest, BindingResult result, @PathVariable("kudosId") Long kudosId) {
logger.info("New request " + newPlusOneRequest.toString());
if (result.hasErrors()) {
throw new IllegalArgumentException("Invalid request data " + result.toString());
}
Kudos kudos = kudosRepository.findOne(kudosId);
if(kudos == null) {
throw new IllegalArgumentException("There is no kudos with id=" + kudosId);
}
PlusOne plusOne = new PlusOne(
slackUsersProvider.mapSlackUserNameToUserId(newPlusOneRequest.getUserName()),
newPlusOneRequest.getDescription(),
kudos
);
plusOneRepository.save(plusOne);
kudos.addPlusOne(plusOne);
return new ResponseMessage("ok");
}
项目:spring-cloud-stream
文件:PartitionCapableBinderTests.java
@Test
public void testOneRequiredGroup() throws Exception {
B binder = getBinder();
PP producerProperties = createProducerProperties();
DirectChannel output = createBindableChannel("output", createProducerBindingProperties(producerProperties));
String testDestination = "testDestination" + UUID.randomUUID().toString().replace("-", "");
producerProperties.setRequiredGroups("test1");
Binding<MessageChannel> producerBinding = binder.bindProducer(testDestination, output, producerProperties);
String testPayload = "foo-" + UUID.randomUUID().toString();
output.send(MessageBuilder.withPayload(testPayload).setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build());
QueueChannel inbound1 = new QueueChannel();
Binding<MessageChannel> consumerBinding = binder.bindConsumer(testDestination, "test1", inbound1,
createConsumerProperties());
Message<?> receivedMessage1 = receive(inbound1);
assertThat(receivedMessage1).isNotNull();
assertThat(new String((byte[]) receivedMessage1.getPayload())).isEqualTo(testPayload);
producerBinding.unbind();
consumerBinding.unbind();
}
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testSendWithDefaultContentType() throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
SourceApplication.class, "--server.port=0",
"--spring.jmx.enabled=false")) {
MessageCollector collector = context.getBean(MessageCollector.class);
Source source = context.getBean(Source.class);
User user = new User("Alice");
source.output().send(MessageBuilder.withPayload(user).build());
Message<String> message = (Message<String>) collector
.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
User received = mapper.readValue(message.getPayload(), User.class);
assertThat(
message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.APPLICATION_JSON));
assertThat(user.getName()).isEqualTo(received.getName());
}
}
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testSendJsonAsString() throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
SourceApplication.class, "--server.port=0",
"--spring.jmx.enabled=false")) {
MessageCollector collector = context.getBean(MessageCollector.class);
Source source = context.getBean(Source.class);
User user = new User("Alice");
String json = mapper.writeValueAsString(user);
source.output().send(MessageBuilder.withPayload(user).build());
Message<String> message = (Message<String>) collector
.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
assertThat(
message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.APPLICATION_JSON));
assertThat(json).isEqualTo(message.getPayload());
}
}
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testSendJsonString() throws Exception{
try (ConfigurableApplicationContext context = SpringApplication.run(
SourceApplication.class, "--server.port=0",
"--spring.jmx.enabled=false")) {
MessageCollector collector = context.getBean(MessageCollector.class);
Source source = context.getBean(Source.class);
source.output().send(MessageBuilder.withPayload("foo").build());
Message<String> message = (Message<String>) collector
.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
assertThat(
message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.APPLICATION_JSON));
assertThat("foo").isEqualTo(message.getPayload());
}
}
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testSendBynaryData() throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
SourceApplication.class, "--server.port=0",
"--spring.jmx.enabled=false")) {
MessageCollector collector = context.getBean(MessageCollector.class);
Source source = context.getBean(Source.class);
byte[] data = new byte[] { 0, 1, 2, 3 };
source.output().send(MessageBuilder.withPayload(data).setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_OCTET_STREAM).build());
Message<byte[]> message = (Message<byte[]>) collector
.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
assertThat(
message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.APPLICATION_OCTET_STREAM));
assertThat(message.getPayload()).isEqualTo(data);
}
}
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testSendBinaryDataWithContentTypeUsingHeaders() throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
SourceApplication.class, "--server.port=0",
"--spring.jmx.enabled=false")) {
MessageCollector collector = context.getBean(MessageCollector.class);
Source source = context.getBean(Source.class);
byte[] data = new byte[] { 0, 1, 2, 3 };
source.output().send(MessageBuilder.withPayload(data)
.setHeader(MessageHeaders.CONTENT_TYPE,MimeTypeUtils.IMAGE_JPEG)
.build());
Message<byte[]> message = (Message<byte[]>) collector
.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.IMAGE_JPEG));
assertThat(message.getPayload()).isEqualTo(data);
}
}
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testSendStringType() throws Exception{
try (ConfigurableApplicationContext context = SpringApplication.run(
SourceApplication.class, "--server.port=0",
"--spring.jmx.enabled=false",
"--spring.cloud.stream.bindings.output.contentType=text/plain")) {
MessageCollector collector = context.getBean(MessageCollector.class);
Source source = context.getBean(Source.class);
User user = new User("Alice");
source.output().send(MessageBuilder.withPayload(user).build());
Message<String> message = (Message<String>) collector
.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.TEXT_PLAIN));
assertThat(message.getPayload()).isEqualTo(user.toString());
}
}
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testReceiveWithDefaults() throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
SinkApplication.class, "--server.port=0",
"--spring.jmx.enabled=false")) {
TestSink testSink = context.getBean(TestSink.class);
SinkApplication sourceApp = context.getBean(SinkApplication.class);
User user = new User("Alice");
testSink.pojo().send(MessageBuilder.withPayload(mapper.writeValueAsBytes(user)).build());
Map<String,Object> headers = (Map<String, Object>) sourceApp.arguments.pop();
User received = (User)sourceApp.arguments.pop();
assertThat(((MimeType)headers.get(MessageHeaders.CONTENT_TYPE))
.includes(MimeTypeUtils.APPLICATION_JSON));
assertThat(user.getName()).isEqualTo(received.getName());
}
}
项目:spring-cloud-stream
文件:ContentTypeTests.java
@Test
public void testReceiveRawWithDifferentContentTypes() throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
SinkApplication.class, "--server.port=0",
"--spring.jmx.enabled=false")) {
TestSink testSink = context.getBean(TestSink.class);
SinkApplication sourceApp = context.getBean(SinkApplication.class);
testSink.raw().send(MessageBuilder.withPayload(new byte[4])
.setHeader(MessageHeaders.CONTENT_TYPE,MimeTypeUtils.IMAGE_JPEG)
.build());
testSink.raw().send(MessageBuilder.withPayload(new byte[4])
.setHeader(MessageHeaders.CONTENT_TYPE,MimeTypeUtils.IMAGE_GIF)
.build());
Map<String,Object> headers = (Map<String, Object>) sourceApp.arguments.pop();
sourceApp.arguments.pop();
assertThat(((MimeType)headers.get(MessageHeaders.CONTENT_TYPE))
.includes(MimeTypeUtils.IMAGE_GIF));
headers = (Map<String, Object>) sourceApp.arguments.pop();
sourceApp.arguments.pop();
assertThat(((MimeType)headers.get(MessageHeaders.CONTENT_TYPE))
.includes(MimeTypeUtils.IMAGE_JPEG));
}
}
项目:spring-cloud-stream
文件:StreamListenerHandlerBeanTests.java
@Test
@SuppressWarnings("unchecked")
public void testHandlerBean() throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(this.configClass,
"--spring.cloud.stream.bindings.output.contentType=application/json",
"--server.port=0");
MessageCollector collector = context.getBean(MessageCollector.class);
Processor processor = context.getBean(Processor.class);
String id = UUID.randomUUID().toString();
processor.input().send(
MessageBuilder.withPayload("{\"foo\":\"barbar" + id + "\"}")
.setHeader("contentType", "application/json").build());
HandlerBean handlerBean = context.getBean(HandlerBean.class);
Assertions.assertThat(handlerBean.receivedPojos).hasSize(1);
Assertions.assertThat(handlerBean.receivedPojos.get(0)).hasFieldOrPropertyWithValue("foo",
"barbar" + id);
Message<String> message = (Message<String>) collector.forChannel(
processor.output()).poll(1, TimeUnit.SECONDS);
assertThat(message).isNotNull();
assertThat(message.getPayload()).isEqualTo("{\"bar\":\"barbar" + id + "\"}");
assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.APPLICATION_JSON));
context.close();
}
项目:spring-cloud-stream
文件:StreamListenerMethodReturnWithConversionTests.java
@Test
@SuppressWarnings("unchecked")
public void testReturnConversion() throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(this.configClass,
"--spring.cloud.stream.bindings.output.contentType=application/json", "--server.port=0","--spring.jmx.enabled=false");
MessageCollector collector = context.getBean(MessageCollector.class);
Processor processor = context.getBean(Processor.class);
String id = UUID.randomUUID().toString();
processor.input().send(MessageBuilder.withPayload("{\"foo\":\"barbar" + id + "\"}")
.setHeader("contentType", "application/json").build());
TestPojoWithMimeType testPojoWithMimeType = context.getBean(TestPojoWithMimeType.class);
Assertions.assertThat(testPojoWithMimeType.receivedPojos).hasSize(1);
Assertions.assertThat(testPojoWithMimeType.receivedPojos.get(0)).hasFieldOrPropertyWithValue("foo", "barbar" + id);
Message<String> message = (Message<String>) collector.forChannel(processor.output()).poll(1,
TimeUnit.SECONDS);
assertThat(message).isNotNull();
assertThat(new String(message.getPayload())).isEqualTo("{\"bar\":\"barbar" + id + "\"}");
assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.APPLICATION_JSON));
context.close();
}
项目:grassroot-platform
文件:TodoWebViewModifyController.java
@RequestMapping(value = "export")
public void exportResponses(@RequestParam String todoUid, HttpServletResponse response) throws IOException {
log.info("exporting tood responses .. ");
String fileName = "todo_responses.xlsx";
response.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
XSSFWorkbook xls = memberData.exportTodoData(getUserProfile().getUid(), todoUid);
log.info("got a workbook back, looks like: {}", xls);
xls.write(response.getOutputStream());
response.flushBuffer();
}
项目:grassroot-platform
文件:UserProfileController.java
@RequestMapping(value = "export-groups", method = RequestMethod.POST)
public void exportGroupsDo(@RequestParam String[] selectedGroupUids, HttpServletResponse response) throws IOException {
User user = getUserProfile();
user = userManagementService.load(user.getUid()); // take fresh copy in order to have groups added since login
List<Group> userGroups = user.getGroups().stream().filter(Group::isActive).sorted(Comparator.comparing(Group::getGroupName)).collect(Collectors.toList());
List<String> userGroupUids = userGroups.stream().map(Group::getUid).collect(Collectors.toList());
XSSFWorkbook xls = memberDataExportBroker.exportMultipleGroupMembers(userGroupUids, Arrays.asList(selectedGroupUids));
String fileName = "multiple_group_members.xlsx";
response.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
xls.write(response.getOutputStream());
response.flushBuffer();
}
项目:metl
文件:AbstractSerializer.java
protected String getDetectedFormat() {
String detectedFormat = null;
if (format.equals(FORMAT_AUTOMATIC)) {
if (FORMAT_XML.equalsIgnoreCase(context.getFlowParameters().get(FORMAT))) {
detectedFormat = FORMAT_XML;
} else if (FORMAT_JSON.equalsIgnoreCase(context.getFlowParameters().get(FORMAT))) {
detectedFormat = FORMAT_JSON;
} else if (MimeTypeUtils.APPLICATION_XML.toString()
.equals(context.getFlowParameters().get(HttpHeaders.CONTENT_TYPE))) {
detectedFormat = FORMAT_XML;
} else if (MimeTypeUtils.APPLICATION_JSON.toString()
.equals(context.getFlowParameters().get(HttpHeaders.CONTENT_TYPE))) {
detectedFormat = FORMAT_JSON;
} else if (MimeTypeUtils.APPLICATION_XML.toString()
.equals(context.getFlowParameters().get(HttpHeaders.ACCEPT))) {
detectedFormat = FORMAT_XML;
} else {
detectedFormat = FORMAT_JSON;
}
}
return detectedFormat;
}
项目:janusz-backend
文件:KudosRestController.java
@RequestMapping(value = "/{kudosId}/plusOnes", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseMessage addNewPlusOne(@RequestBody @Valid NewPlusOneRequest newPlusOneRequest, BindingResult result, @PathVariable("kudosId") Long kudosId) {
logger.info("New request " + newPlusOneRequest.toString());
if (result.hasErrors()) {
throw new IllegalArgumentException("Invalid request data " + result.toString());
}
Kudos kudos = kudosRepository.findOne(kudosId);
if(kudos == null) {
throw new IllegalArgumentException("There is no kudos with id=" + kudosId);
}
PlusOne plusOne = new PlusOne(
slackUsersProvider.mapSlackUserNameToUserId(newPlusOneRequest.getUserName()),
newPlusOneRequest.getDescription(),
kudos
);
plusOneRepository.save(plusOne);
kudos.addPlusOne(plusOne);
return new ResponseMessage("ok");
}
项目:spring-cloud-sockets
文件:ReactiveSocketClient.java
private AbstractRemoteHandler handlerFor(Method method){
AbstractRemoteHandler handler = remoteHandlers.get(method);
if(handler != null){
return handler;
}
synchronized (remoteHandlers){
ServiceMethodInfo serviceMethodInfo = new ServiceMethodInfo(method);
Converter converter = converters.stream().filter(payloadConverter -> payloadConverter.accept(serviceMethodInfo.getMappingInfo().getMimeType())).findFirst().orElseThrow(IllegalStateException::new);
Converter metadataConverter = converters.stream().filter(binaryConverter -> binaryConverter.accept(MimeTypeUtils.APPLICATION_JSON)).findFirst().orElseThrow(IllegalStateException::new);
switch (serviceMethodInfo.getMappingInfo().getExchangeMode()){
case ONE_WAY:
handler = new OneWayRemoteHandler(socket, serviceMethodInfo);
remoteHandlers.put(method, handler);
break;
case REQUEST_ONE:
handler = new RequestOneRemoteHandler(socket, serviceMethodInfo);
remoteHandlers.put(method, handler);
break;
case REQUEST_MANY:
handler = new RequestManyRemoteHandler(socket, serviceMethodInfo);
remoteHandlers.put(method, handler);
break;
case REQUEST_STREAM:
handler = new RequestStreamRemoteHandler(socket, serviceMethodInfo);
remoteHandlers.put(method, handler);
break;
}
handler.setPayloadConverter(converter);
handler.setMetadataConverter(metadataConverter);
}
return handler;
}
项目:spring-boot-starter-rocketmq
文件:RocketMQTemplate.java
@Override
protected Message<?> doConvert(Object payload, Map<String, Object> headers, MessagePostProcessor postProcessor) {
String content;
if (payload instanceof String) {
content = (String) payload;
} else {
// if payload not as string, use objectMapper change it.
try {
content = objectMapper.writeValueAsString(payload);
} catch (JsonProcessingException e) {
log.info("convert payload to String failed. payload:{}", payload);
throw new RuntimeException("convert to payload to String failed.", e);
}
}
MessageBuilder<?> builder = MessageBuilder.withPayload(content);
if (headers != null) {
builder.copyHeaders(headers);
}
builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN);
Message<?> message = builder.build();
if (postProcessor != null) {
message = postProcessor.postProcessMessage(message);
}
return message;
}
项目:spring-mvc-error-handling-example
文件:CustomErrorController.java
@RequestMapping(produces = MimeTypeUtils.TEXT_PLAIN_VALUE)
@ResponseBody
public String errorTextPlan(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
body.put("status", getStatus(request));
return body.toString();
}
项目:matrix-appservice-email
文件:EmailFormatterOutboud.java
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, boolean allowReply) throws IOException, MessagingException {
List<_BridgeMessageContent> contents = Arrays.asList(
new BridgeMessageContent(MimeTypeUtils.TEXT_PLAIN_VALUE),
new BridgeMessageContent(MimeTypeUtils.TEXT_HTML_VALUE)
);
return makeEmail(data, template, contents, allowReply);
}
项目:matrix-appservice-email
文件:EmailFormatterInbound.java
protected List<_BridgeMessageContent> extractContent(Part p) throws MessagingException, IOException {
if (p.isMimeType("multipart/*")) {
log.info("Found multipart content, extracting");
List<_BridgeMessageContent> contents = new ArrayList<>();
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++) {
contents.addAll(extractContent(mp.getBodyPart(i)));
}
return contents;
}
if (p.isMimeType("message/rfc822")) {
log.info("Found nested content, extracting");
return extractContent((Part) p.getContent());
}
String content = p.getContent().toString();
String[] encodings = p.getHeader("Content-Transfer-Encoding");
String encoding = (encodings != null && encodings.length > 0) ? encodings[0] : null;
if (StringUtils.equalsIgnoreCase("quoted-printable", encoding)) {
try {
// TODO actually extract the charset properly
// TODO read RFC to know default charset
log.info("Transfer encoding is {}, decoding", encoding);
content = new String(QuotedPrintableCodec.decodeQuotedPrintable(content.getBytes()));
} catch (DecoderException e) {
log.warn("Content transfer encoding is set to {} but enable to decode: {}", encoding, e.getMessage());
}
}
if (p.isMimeType(MimeTypeUtils.TEXT_PLAIN_VALUE)) {
log.info("Found plain text content");
return Collections.singletonList(new BridgeMessageTextContent(content, encoding));
}
if (p.isMimeType(MimeTypeUtils.TEXT_HTML_VALUE)) {
log.info("Found HTML content");
return Collections.singletonList(new BridgeMessageHtmlContent(content, encoding));
}
return Collections.emptyList();
}
项目:smarti
文件:RocketChatEndpoint.java
/**
* Called by rocket.chat plugins to get the conversationId for the clientId and channelId known to the plugin.
* The returned conversationID can later be used for calls to the {@link ConversationWebservice}
* @param clientName the client id
* @param channelId the channelId
* @return a <code>200</code> with the conversation id as payload or a <code>404</code> if no conversation is
* active for the parsed parameters.
*/
@ApiOperation(value = "retrieve a conversation ID for a channel and client id", nickname = "rocketGetConversation",
produces=MimeTypeUtils.TEXT_PLAIN_VALUE
)
@RequestMapping(value = "{clientId}/{channelId}/conversationid", method = RequestMethod.GET,
produces=MimeTypeUtils.TEXT_PLAIN_VALUE, consumes=MimeTypeUtils.ALL_VALUE)
public ResponseEntity<?> getConversation(
AuthContext authContext,
@PathVariable(value="clientId") String clientName,
@PathVariable(value="channelId") String channelId) {
if (log.isTraceEnabled()) {
log.debug("{}[{}]: lookup conversation-id of {}", clientName, authContext, channelId);
} else {
log.debug("{}: lookup conversation-id of {}", clientName, channelId);
}
Client client = clientService.getByName(clientName);
if(client == null || !authenticationService.hasAccessToClient(authContext, client.getId())){
return ResponseEntity.notFound().build();
}
Conversation conversation = conversationService.getCurrentConversationByChannelId(
client, createChannelId(client, channelId),() -> null); //do not create new conversations
if (conversation == null || conversation.getId() == null) {
return ResponseEntity.notFound().build();
} else {
return ResponseEntity.ok(conversation.getId().toHexString());
}
}
项目:smarti
文件:ConversationWebservice.java
@ApiOperation(value = "append a message to the conversation", response = Conversation.class)
@RequestMapping(value = "{id}/message", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addMessage(
AuthContext authContext,
@PathVariable("id") ObjectId id,
@RequestBody Message message
) {
final Conversation conversation = authenticationService.assertConversation(authContext, id);
final Client client = authenticationService.assertClient(authContext, conversation.getOwner());
return ResponseEntity.ok(conversationService.appendMessage(client, conversation, message));
}
项目:smarti
文件:ConversationWebservice.java
@ApiOperation(value = "update a query based on new slot-assignments", response = Query.class)
@RequestMapping(value = "{id}/query/{template}/{creator}", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getQuery(
AuthContext authContext,
@PathVariable("id") ObjectId id,
@PathVariable("template") int templateIdx,
@PathVariable("creator") String creator,
@ApiParam(hidden = true) @RequestParam(required = false) MultiValueMap<String, String> params,
@RequestBody QueryUpdate queryUpdate
) {
final Conversation conversation = authenticationService.assertConversation(authContext, id);
final Client client = authenticationService.assertClient(authContext, conversation.getOwner());
final Configuration clientConf = configService.getClientConfiguration(client.getId());
if(clientConf == null){
log.info("Client {} of Conversation {} has no longer a configuration assigned ... returning 404 NOT FOUND",
conversation.getChannelId(), conversation.getId());
return ResponseEntity.notFound().build();
}
final Template template = conversation.getTemplates().get(templateIdx);
if (template == null) return ResponseEntity.notFound().build();
//NOTE: conversationService.getConversation(..) already update the queries if necessary
//so at this place we only need to retrieve the requested query
Optional<Query> query = template.getQueries().stream().filter(q -> Objects.equals(creator, q.getCreator())).findFirst();
return query.isPresent() ? ResponseEntity.ok(query.get()) : ResponseEntity.notFound().build();
}
项目:smarti
文件:UserWebservice.java
@RequestMapping(value = "/user", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<SmartiUserData> createUser(AuthContext authContext,
@RequestBody SmartiUserData user) {
authenticationService.assertRole(authContext, AuthenticationService.ADMIN);
if (StringUtils.isBlank(user.getLogin())) {
return ResponseEntity.unprocessableEntity().build();
}
return ResponseEntity.ok(SmartiUserData.fromModel(userService.createUser(user.toModel())));
}
项目:smarti
文件:UserWebservice.java
@RequestMapping(value = "/user/{login}", method = RequestMethod.PUT, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
public SmartiUserData updateUser(AuthContext authentication,
@PathVariable("login") String login,
@RequestBody SmartiUserData user) {
// Access only for ADMIN or @me
if (authenticationService.hasLogin(authentication, login)
|| authenticationService.hasRole(authentication, AuthenticationService.ADMIN)) {
return SmartiUserData.fromModel(userService.updateProfile(login, user.getProfile()));
} else {
throw new AccessDeniedException("No access for " + authentication);
}
}
项目:smarti
文件:ConversationAdminWebservice.java
@ApiOperation(value = "import conversations")
@RequestMapping(value = "import", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<?> importConversations(
AuthContext authContext,
@RequestParam("owner") ObjectId owner,
@RequestParam(value = "replace", defaultValue = "false", required = false) boolean replace,
@RequestBody List<Conversation> conversations
) {
if (authenticationService.hasAccessToClient(authContext, owner)) {
conversationService.importConversations(owner, conversations, replace);
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.badRequest().build();
}
}
项目:spring4-understanding
文件:StompHeaderAccessor.java
void updateSimpMessageHeadersFromStompHeaders() {
if (getNativeHeaders() == null) {
return;
}
String value = getFirstNativeHeader(STOMP_DESTINATION_HEADER);
if (value != null) {
super.setDestination(value);
}
value = getFirstNativeHeader(STOMP_CONTENT_TYPE_HEADER);
if (value != null) {
super.setContentType(MimeTypeUtils.parseMimeType(value));
}
StompCommand command = getCommand();
if (StompCommand.MESSAGE.equals(command)) {
value = getFirstNativeHeader(STOMP_SUBSCRIPTION_HEADER);
if (value != null) {
super.setSubscriptionId(value);
}
}
else if (StompCommand.SUBSCRIBE.equals(command) || StompCommand.UNSUBSCRIBE.equals(command)) {
value = getFirstNativeHeader(STOMP_ID_HEADER);
if (value != null) {
super.setSubscriptionId(value);
}
}
else if (StompCommand.CONNECT.equals(command)) {
protectPasscode();
}
}