I am trying to develop an AWS Lambda function that is triggered by events from SQS.
I am using the spring-cloud-function-adapter-aws (version 1.0.0.RELEASE) and in specifically a SpringBootRequestHandler.
However, the ObjectMapper that is being used is case-sensitive and therefore failing to successful convert the Json coming from SQS.
SQS publishes the following Json and it is the Records field in particular that I'm having the problem with.
{
"Records": [
{
"body": "Hello from SQS!",
"receiptHandle": "MessageReceiptHandle",
"md5OfBody": "7b270e59b47ff90a553787216d55d91d",
"eventSourceARN": "arn:aws:sqs:eu-west-1:123456789012:MyQueue",
"eventSource": "aws:sqs",
"awsRegion": "eu-west-1",
"messageId": "19dd0b57-b21e-4ac1-bd88-01bbb068cb78",
"attributes": {
"ApproximateFirstReceiveTimestamp": "1523232000001",
"SenderId": "123456789012",
"ApproximateReceiveCount": "1",
"SentTimestamp": "1523232000000"
},
"messageAttributes": {}
}
]
}
I have tried the suggestions in this question, but to no avail. Configuring ObjectMapper in Spring
In my POJO, I've also added the below annotation but it isn't working either whilst it would outside of Lambda.
#JsonProperty("Records")
private List<SqsRecord> Records;
Any help would be much appreciated.
My Lambda handler is defined as:
public class SqsEventHandler extends SpringBootRequestHandler<SqsEvent, String> {}
The POJO defined as:
public class SqsEvent {
#JsonProperty("Records")
private List<SqsRecord> records;
#Data
public class SqsRecord {
private String body;
private String receiptHandle;
private String md5OfBody;
private String eventSourceARN;
private String eventSource;
private String awsRegion;
private String messageId;
}
}
I expect the Json from the sample message to be able to be read in by the ObjectMapper, but the field "records" is null.
I got this issue solved in a more simple manner.
Referencing https://docs.aws.amazon.com/lambda/latest/dg/java-handler-io-type-stream.html and in specific
if Lambda's serialization approach does not meet your needs, you can use the byte stream implementation
I am now using the SpringBootStreamHandler directly and I have created an ObjectMapper instance with my required configuration options in my Spring Configuration class as:
#Bean
public ObjectMapper objectMapper() {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
we've got this problem with a lot of AWS services.
You must define a new mapper like this :
SQSMixin :
private static interface SQSEventMixin {
public static final String ATTRIBUTES = "attributes";
public static final String AWS_REGION = "awsRegion";
public static final String BODY = "body";
public static final String EVENT_SOURCE = "eventSource";
public static final String EVENT_SOURCE_ARN = "eventSourceARN";
public static final String MD5_OF_BOBY = "md5OfBody";
public static final String MD5_OF_MESSAGE_ATTRIBUTES = "md5OfMessageAttributes";
public static final String MESSAGE_ID = "messageId";
public static final String RECEIPT_HANDLE = "receiptHandle";
#JsonProperty(value = "Records")
public List<?> getRecords();
static interface MessageMixin {
#JsonProperty(ATTRIBUTES)
public String getAttributes();
#JsonProperty(ATTRIBUTES)
public void setAttributes(String attributes);
#JsonProperty(AWS_REGION)
public String getAwsRegion();
#JsonProperty(AWS_REGION)
public void setAwsRegion(String awsRegion);
#JsonProperty(BODY)
public Object getBody();
#JsonProperty(BODY)
public void setBody(Object body);
#JsonProperty(EVENT_SOURCE)
public String getEventSource();
#JsonProperty(EVENT_SOURCE)
public void setEventSource(String eventSource);
#JsonProperty(EVENT_SOURCE_ARN)
public String getEventSourceArn();
#JsonProperty(EVENT_SOURCE_ARN)
public void setEventSourceArn(String eventSourceArn);
#JsonProperty(MD5_OF_BOBY)
public String getMd5OfBody();
#JsonProperty(MD5_OF_BOBY)
public void setMd5OfBody(String md5OfBody);
#JsonProperty(MD5_OF_MESSAGE_ATTRIBUTES)
public String getMd5OfMessageAttributes();
#JsonProperty(MD5_OF_MESSAGE_ATTRIBUTES)
public void setMd5OfMessageAttributes(String md5OfMessageAttributes);
#JsonProperty(MESSAGE_ID)
public String getMessageId();
#JsonProperty(MESSAGE_ID)
public void setMessageId(String messageId);
#JsonProperty(RECEIPT_HANDLE)
public String getReceiptHandle();
#JsonProperty(RECEIPT_HANDLE)
public void setReceiptHandle(String receiptHandle);
}
}
A Strategy for record :
private static class UpperCaseRecordsPropertyNamingStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase {
private static final long serialVersionUID = 1L;
#Override
public String translate(String propertyName) {
if (propertyName.equals("records")) {
return "Records";
}
return propertyName;
}
}
Formatter for Date :
private static final DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime()
.withZone(new FixedDateTimeZone("GMT", "GMT", 0, 0));
private static class DateTimeMapperModule extends SimpleModule {
private static final long serialVersionUID = 1L;
public DateTimeMapperModule() {
super("DateTimeMapperModule");
super.addSerializer(DateTime.class, new DateTimeSerializer());
super.addDeserializer(DateTime.class, new DateTimeDeserializer());
}
}
private static class DateTimeSerializer extends JsonSerializer<DateTime> {
#Override
public void serialize(DateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeString(dateTimeFormatter.print(value));
}
}
private static class DateTimeDeserializer extends JsonDeserializer<DateTime> {
#Override
public DateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
return dateTimeFormatter.parseDateTime(parser.getText());
}
}
And declare your mapper :
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
mapper.setPropertyNamingStrategy(new UpperCaseRecordsPropertyNamingStrategy());
mapper.registerModule(new DateTimeMapperModule());
mapper.addMixIn(SQSMessage.class, SQSEventMixin.MessageMixin.class);
SQSEvent request = mapper.convertValue(inputObject, SQSEvent.class);
There is already an official library that is supporting this: https://aws.amazon.com/blogs/opensource/testing-aws-lambda-functions-written-in-java/
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-tests</artifactId>
<version>1.0.0</version>
<scope>test</scope>
</dependency>
Also have surefire in your plugins:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
Example:
SQSEvent input = EventLoader.loadEvent("/sqsEvent.json", SQSEvent.class);
Eclipse gave option to auto generate the toString method for every class.
Further leverage this facility, I am creating String Format Template to give as Json format when eclipse generate toString Method.
I used following String Format Template:
{ ${member.name()}:"${member.value}", ${otherMembers}}
now i generated toString method as following POJO but When i run this program i got result as and not a VALID JSON.
{ name:"null", reportees:"[1, 2, 3]", department:"[retail, banking, finance]", owns:"null", supplimentary:"null}
Code
public class TestPojo {
private String name;
private List<String> reportees;
private String[] department;
private Machine owns;
private List<Machine> supplimentary;
public static void main(String arg[]) {
TestPojo aTestPojo = new TestPojo();
aTestPojo.department = new String[] { "retail", "banking", "finance" };
aTestPojo.reportees = new ArrayList<String>() {
{
add("1");
add("2");
add("3");
}
};
System.out.print(aTestPojo);
}
public static class Machine {
private String machineName;
private String duties;
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
public String getDuties() {
return duties;
}
public void setDuties(String duties) {
this.duties = duties;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{ machineName:\"").append(machineName).append("\", duties:\"").append(duties).append("}");
return builder.toString();
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{ name:\"").append(name).append("\", reportees:\"").append(reportees).append("\", department:\"").append(Arrays.toString(department)).append("\", owns:\"").append(owns).append("\", supplimentary:\"").append(supplimentary).append("}");
return builder.toString();
}
}
With the help of #dvlcube idea. I built a "Eclipse Custom toString() builder" to generate toString method code to return a JSON formatted string of current object.
Follow the github for this solution Click [Eclipse toString_Builder for JSON](https://github.com/djaganathan/EclipseToStringBuilderForJson/blob/master/src/main/java/com/github/djaganathan/opensource/eclipse/util/JsonToStringBuilder.java,"Custom Eclipse toString() Builder")
Sample Testing Code
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.time.StopWatch;
import org.elasticsearch.common.collect.Lists;
public class TestPojo {
private String name;
private List<String> reportees;
private String[] department;
private Machine owns;
private List<Machine> supplimentary;
private int i = 10;
private Map<String, Machine> machineList = Maps.newConcurrentMap();
public static void main(String arg[]) {
TestPojo aTestPojo = new TestPojo();
aTestPojo.department = new String[] { "retail", "banking", "finance"};
aTestPojo.reportees = new ArrayList<String>() {
{
add("1");
add("2");
add("3");
}
};
Machine aMachine = new Machine("Train", "travel");
Machine aMachine1 = new Machine("Lorry", "Carrier");
aTestPojo.supplimentary = Lists.newArrayList(aMachine, aMachine1);
aTestPojo.machineList.put("Train", aMachine);
aTestPojo.machineList.put("Lorry", aMachine1);
System.out.print(aTestPojo);
}
public static class Machine {
private String machineName;
private String duties;
public Machine(String machineName, String duties) {
super();
this.machineName = machineName;
this.duties = duties;
}
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
public String getDuties() {
return duties;
}
public void setDuties(String duties) {
this.duties = duties;
}
#Override
public String toString() {
JsonToStringBuilder builder = new JsonToStringBuilder(this);
builder.append("machineName", machineName);
builder.append("duties", duties);
return builder.build();
}
}
#Override
public String toString() {
JsonToStringBuilder builder = new JsonToStringBuilder(this);
builder.append("name", name);
builder.append("reportees", reportees);
builder.append("department", department);
builder.append("owns", owns);
builder.append("supplimentary", supplimentary);
builder.append("i", i);
builder.append("machineList", machineList);
String value = builder.build();
return value;
}
}
While running this program i got the following JSON output
{"name": null,"reportees": ["1","2","3"],"department": ["retail","banking","finance"],"owns": null,"supplimentary": [{"machineName": "Train","duties": "travel"},{"machineName": "Lorry","duties": "Carrier"}],"i": 10,"machineList": {"Lorry": {"machineName": "Lorry","duties": "Carrier"},"Train": {"machineName": "Train","duties": "travel"}}}
It's not valid JSON because of the way arrays and collections are being printed ("[1,2,3]" instead of ["1","2","3"]).
Also, it wouldn't pass strict JSON validation because the field names should be quoted as well.
Eclipse's String Format Template can be very useful, but for full control it's better to create a builder class.
Here's a gist for doing just that. You can expand on it, and it works for your example class out of the box.
You can use this class to generate the toString() methods in Eclipse.
Recommended only for String values. Below expression gives you as a JSON toString generation.
{"${member.name()}":"${member.value}", "${otherMembers}"}
I have checked answer here, but here first they are saving it to some place and then reading it's stream and trying to check Mime type of that file
Get real file extension -Java code
But I want to know the file type before even saving it to the hard disk or at some place.
I know I can do it in these 2 more ways
File savedFile = new File(fileHandler.createTodayFolder(fileLocation) + "/" + name);
Path path = Paths.get(file.get);
Tika tika = new Tika();
String checkType = tika.detect(path.toFile());
and
Path path = Paths.get(savedFile.getPath());
Files.probeContentType(path)
But in these both cases they are using somefile which is already at some location in hard disk.
I want code something like this
public #ResponseBody ResponseEntity<?> importResume(#RequestParam(value = "name", required = false) String name,
#RequestParam("file") MultipartFile file) {
if (file!=DESIRED_TYPE)
{
return Exception;
}
}
Is there any way of doing this ???
For me, the cleanest solution:
using FilenameUtils of org.apache.commons.io:
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
You can use Tika https://tika.apache.org/
//file is a MultipartFile
if(!file.isEmpty)
{
Tika tika = new Tika();
String detectedType = tika.detect(file.getBytes());
System.out.println(detectedType);
}
This should get you the mimetype without saving the file
Given the String filename, you can do:
filename.substring(filename.lastIndexOf(".") + 1);
You can map the mimetype to a existing extension by making a map...
You can use apache.mime.types for create one like it's done here:
http://www.java2s.com/Code/Java/Network-Protocol/MapfileextensionstoMIMEtypesBasedontheApachemimetypesfile.htm
public class MimeTypes {
public static final String MIME_APPLICATION_ANDREW_INSET = "application/andrew-inset";
public static final String MIME_APPLICATION_JSON = "application/json";
public static final String MIME_APPLICATION_ZIP = "application/zip";
public static final String MIME_APPLICATION_X_GZIP = "application/x-gzip";
public static final String MIME_APPLICATION_TGZ = "application/tgz";
public static final String MIME_APPLICATION_MSWORD = "application/msword";
public static final String MIME_APPLICATION_POSTSCRIPT = "application/postscript";
public static final String MIME_APPLICATION_PDF = "application/pdf";
public static final String MIME_APPLICATION_JNLP = "application/jnlp";
public static final String MIME_APPLICATION_MAC_BINHEX40 = "application/mac-binhex40";
public static final String MIME_APPLICATION_MAC_COMPACTPRO = "application/mac-compactpro";
public static final String MIME_APPLICATION_MATHML_XML = "application/mathml+xml";
public static final String MIME_APPLICATION_OCTET_STREAM = "application/octet-stream";
public static final String MIME_APPLICATION_ODA = "application/oda";
public static final String MIME_APPLICATION_RDF_XML = "application/rdf+xml";
public static final String MIME_APPLICATION_JAVA_ARCHIVE = "application/java-archive";
public static final String MIME_APPLICATION_RDF_SMIL = "application/smil";
public static final String MIME_APPLICATION_SRGS = "application/srgs";
public static final String MIME_APPLICATION_SRGS_XML = "application/srgs+xml";
public static final String MIME_APPLICATION_VND_MIF = "application/vnd.mif";
public static final String MIME_APPLICATION_VND_MSEXCEL = "application/vnd.ms-excel";
public static final String MIME_APPLICATION_VND_MSPOWERPOINT= "application/vnd.ms-powerpoint";
public static final String MIME_APPLICATION_VND_RNREALMEDIA = "application/vnd.rn-realmedia";
public static final String MIME_APPLICATION_X_BCPIO = "application/x-bcpio";
public static final String MIME_APPLICATION_X_CDLINK = "application/x-cdlink";
public static final String MIME_APPLICATION_X_CHESS_PGN = "application/x-chess-pgn";
public static final String MIME_APPLICATION_X_CPIO = "application/x-cpio";
public static final String MIME_APPLICATION_X_CSH = "application/x-csh";
public static final String MIME_APPLICATION_X_DIRECTOR = "application/x-director";
public static final String MIME_APPLICATION_X_DVI = "application/x-dvi";
public static final String MIME_APPLICATION_X_FUTURESPLASH = "application/x-futuresplash";
public static final String MIME_APPLICATION_X_GTAR = "application/x-gtar";
public static final String MIME_APPLICATION_X_HDF = "application/x-hdf";
public static final String MIME_APPLICATION_X_JAVASCRIPT = "application/x-javascript";
public static final String MIME_APPLICATION_X_KOAN = "application/x-koan";
public static final String MIME_APPLICATION_X_LATEX = "application/x-latex";
public static final String MIME_APPLICATION_X_NETCDF = "application/x-netcdf";
public static final String MIME_APPLICATION_X_OGG = "application/x-ogg";
public static final String MIME_APPLICATION_X_SH = "application/x-sh";
public static final String MIME_APPLICATION_X_SHAR = "application/x-shar";
public static final String MIME_APPLICATION_X_SHOCKWAVE_FLASH = "application/x-shockwave-flash";
public static final String MIME_APPLICATION_X_STUFFIT = "application/x-stuffit";
public static final String MIME_APPLICATION_X_SV4CPIO = "application/x-sv4cpio";
public static final String MIME_APPLICATION_X_SV4CRC = "application/x-sv4crc";
public static final String MIME_APPLICATION_X_TAR = "application/x-tar";
public static final String MIME_APPLICATION_X_RAR_COMPRESSED= "application/x-rar-compressed";
public static final String MIME_APPLICATION_X_TCL = "application/x-tcl";
public static final String MIME_APPLICATION_X_TEX = "application/x-tex";
public static final String MIME_APPLICATION_X_TEXINFO = "application/x-texinfo";
public static final String MIME_APPLICATION_X_TROFF = "application/x-troff";
public static final String MIME_APPLICATION_X_TROFF_MAN = "application/x-troff-man";
public static final String MIME_APPLICATION_X_TROFF_ME = "application/x-troff-me";
public static final String MIME_APPLICATION_X_TROFF_MS = "application/x-troff-ms";
public static final String MIME_APPLICATION_X_USTAR = "application/x-ustar";
public static final String MIME_APPLICATION_X_WAIS_SOURCE = "application/x-wais-source";
public static final String MIME_APPLICATION_VND_MOZZILLA_XUL_XML = "application/vnd.mozilla.xul+xml";
public static final String MIME_APPLICATION_XHTML_XML = "application/xhtml+xml";
public static final String MIME_APPLICATION_XSLT_XML = "application/xslt+xml";
public static final String MIME_APPLICATION_XML = "application/xml";
public static final String MIME_APPLICATION_XML_DTD = "application/xml-dtd";
public static final String MIME_IMAGE_BMP = "image/bmp";
public static final String MIME_IMAGE_CGM = "image/cgm";
public static final String MIME_IMAGE_GIF = "image/gif";
public static final String MIME_IMAGE_IEF = "image/ief";
public static final String MIME_IMAGE_JPEG = "image/jpeg";
public static final String MIME_IMAGE_TIFF = "image/tiff";
public static final String MIME_IMAGE_PNG = "image/png";
public static final String MIME_IMAGE_SVG_XML = "image/svg+xml";
public static final String MIME_IMAGE_VND_DJVU = "image/vnd.djvu";
public static final String MIME_IMAGE_WAP_WBMP = "image/vnd.wap.wbmp";
public static final String MIME_IMAGE_X_CMU_RASTER = "image/x-cmu-raster";
public static final String MIME_IMAGE_X_ICON = "image/x-icon";
public static final String MIME_IMAGE_X_PORTABLE_ANYMAP = "image/x-portable-anymap";
public static final String MIME_IMAGE_X_PORTABLE_BITMAP = "image/x-portable-bitmap";
public static final String MIME_IMAGE_X_PORTABLE_GRAYMAP = "image/x-portable-graymap";
public static final String MIME_IMAGE_X_PORTABLE_PIXMAP = "image/x-portable-pixmap";
public static final String MIME_IMAGE_X_RGB = "image/x-rgb";
public static final String MIME_AUDIO_BASIC = "audio/basic";
public static final String MIME_AUDIO_MIDI = "audio/midi";
public static final String MIME_AUDIO_MPEG = "audio/mpeg";
public static final String MIME_AUDIO_X_AIFF = "audio/x-aiff";
public static final String MIME_AUDIO_X_MPEGURL = "audio/x-mpegurl";
public static final String MIME_AUDIO_X_PN_REALAUDIO = "audio/x-pn-realaudio";
public static final String MIME_AUDIO_X_WAV = "audio/x-wav";
public static final String MIME_CHEMICAL_X_PDB = "chemical/x-pdb";
public static final String MIME_CHEMICAL_X_XYZ = "chemical/x-xyz";
public static final String MIME_MODEL_IGES = "model/iges";
public static final String MIME_MODEL_MESH = "model/mesh";
public static final String MIME_MODEL_VRLM = "model/vrml";
public static final String MIME_TEXT_PLAIN = "text/plain";
public static final String MIME_TEXT_RICHTEXT = "text/richtext";
public static final String MIME_TEXT_RTF = "text/rtf";
public static final String MIME_TEXT_HTML = "text/html";
public static final String MIME_TEXT_CALENDAR = "text/calendar";
public static final String MIME_TEXT_CSS = "text/css";
public static final String MIME_TEXT_SGML = "text/sgml";
public static final String MIME_TEXT_TAB_SEPARATED_VALUES = "text/tab-separated-values";
public static final String MIME_TEXT_VND_WAP_XML = "text/vnd.wap.wml";
public static final String MIME_TEXT_VND_WAP_WMLSCRIPT = "text/vnd.wap.wmlscript";
public static final String MIME_TEXT_X_SETEXT = "text/x-setext";
public static final String MIME_TEXT_X_COMPONENT = "text/x-component";
public static final String MIME_VIDEO_QUICKTIME = "video/quicktime";
public static final String MIME_VIDEO_MPEG = "video/mpeg";
public static final String MIME_VIDEO_VND_MPEGURL = "video/vnd.mpegurl";
public static final String MIME_VIDEO_X_MSVIDEO = "video/x-msvideo";
public static final String MIME_VIDEO_X_MS_WMV = "video/x-ms-wmv";
public static final String MIME_VIDEO_X_SGI_MOVIE = "video/x-sgi-movie";
public static final String MIME_X_CONFERENCE_X_COOLTALK = "x-conference/x-cooltalk";
private static HashMap<String, String> mimeTypeMapping;
static {
mimeTypeMapping = new HashMap<String, String>(200) {
private void put1(String key, String value) {
if (put(key, value) != null) {
throw new IllegalArgumentException("Duplicated extension: " + key);
}
}
{
put1("xul", MIME_APPLICATION_VND_MOZZILLA_XUL_XML);
put1("json", MIME_APPLICATION_JSON);
put1("ice", MIME_X_CONFERENCE_X_COOLTALK);
put1("movie", MIME_VIDEO_X_SGI_MOVIE);
put1("avi", MIME_VIDEO_X_MSVIDEO);
put1("wmv", MIME_VIDEO_X_MS_WMV);
put1("m4u", MIME_VIDEO_VND_MPEGURL);
put1("mxu", MIME_VIDEO_VND_MPEGURL);
put1("htc", MIME_TEXT_X_COMPONENT);
put1("etx", MIME_TEXT_X_SETEXT);
put1("wmls", MIME_TEXT_VND_WAP_WMLSCRIPT);
put1("wml", MIME_TEXT_VND_WAP_XML);
put1("tsv", MIME_TEXT_TAB_SEPARATED_VALUES);
put1("sgm", MIME_TEXT_SGML);
put1("sgml", MIME_TEXT_SGML);
put1("css", MIME_TEXT_CSS);
put1("ifb", MIME_TEXT_CALENDAR);
put1("ics", MIME_TEXT_CALENDAR);
put1("wrl", MIME_MODEL_VRLM);
put1("vrlm", MIME_MODEL_VRLM);
put1("silo", MIME_MODEL_MESH);
put1("mesh", MIME_MODEL_MESH);
put1("msh", MIME_MODEL_MESH);
put1("iges", MIME_MODEL_IGES);
put1("igs", MIME_MODEL_IGES);
put1("rgb", MIME_IMAGE_X_RGB);
put1("ppm", MIME_IMAGE_X_PORTABLE_PIXMAP);
put1("pgm", MIME_IMAGE_X_PORTABLE_GRAYMAP);
put1("pbm", MIME_IMAGE_X_PORTABLE_BITMAP);
put1("pnm", MIME_IMAGE_X_PORTABLE_ANYMAP);
put1("ico", MIME_IMAGE_X_ICON);
put1("ras", MIME_IMAGE_X_CMU_RASTER);
put1("wbmp", MIME_IMAGE_WAP_WBMP);
put1("djv", MIME_IMAGE_VND_DJVU);
put1("djvu", MIME_IMAGE_VND_DJVU);
put1("svg", MIME_IMAGE_SVG_XML);
put1("ief", MIME_IMAGE_IEF);
put1("cgm", MIME_IMAGE_CGM);
put1("bmp", MIME_IMAGE_BMP);
put1("xyz", MIME_CHEMICAL_X_XYZ);
put1("pdb", MIME_CHEMICAL_X_PDB);
put1("ra", MIME_AUDIO_X_PN_REALAUDIO);
put1("ram", MIME_AUDIO_X_PN_REALAUDIO);
put1("m3u", MIME_AUDIO_X_MPEGURL);
put1("aifc", MIME_AUDIO_X_AIFF);
put1("aif", MIME_AUDIO_X_AIFF);
put1("aiff", MIME_AUDIO_X_AIFF);
put1("mp3", MIME_AUDIO_MPEG);
put1("mp2", MIME_AUDIO_MPEG);
put1("mp1", MIME_AUDIO_MPEG);
put1("mpga", MIME_AUDIO_MPEG);
put1("kar", MIME_AUDIO_MIDI);
put1("mid", MIME_AUDIO_MIDI);
put1("midi", MIME_AUDIO_MIDI);
put1("dtd", MIME_APPLICATION_XML_DTD);
put1("xsl", MIME_APPLICATION_XML);
put1("xml", MIME_APPLICATION_XML);
put1("xslt", MIME_APPLICATION_XSLT_XML);
put1("xht", MIME_APPLICATION_XHTML_XML);
put1("xhtml", MIME_APPLICATION_XHTML_XML);
put1("src", MIME_APPLICATION_X_WAIS_SOURCE);
put1("ustar", MIME_APPLICATION_X_USTAR);
put1("ms", MIME_APPLICATION_X_TROFF_MS);
put1("me", MIME_APPLICATION_X_TROFF_ME);
put1("man", MIME_APPLICATION_X_TROFF_MAN);
put1("roff", MIME_APPLICATION_X_TROFF);
put1("tr", MIME_APPLICATION_X_TROFF);
put1("t", MIME_APPLICATION_X_TROFF);
put1("texi", MIME_APPLICATION_X_TEXINFO);
put1("texinfo", MIME_APPLICATION_X_TEXINFO);
put1("tex", MIME_APPLICATION_X_TEX);
put1("tcl", MIME_APPLICATION_X_TCL);
put1("sv4crc", MIME_APPLICATION_X_SV4CRC);
put1("sv4cpio", MIME_APPLICATION_X_SV4CPIO);
put1("sit", MIME_APPLICATION_X_STUFFIT);
put1("swf", MIME_APPLICATION_X_SHOCKWAVE_FLASH);
put1("shar", MIME_APPLICATION_X_SHAR);
put1("sh", MIME_APPLICATION_X_SH);
put1("cdf", MIME_APPLICATION_X_NETCDF);
put1("nc", MIME_APPLICATION_X_NETCDF);
put1("latex", MIME_APPLICATION_X_LATEX);
put1("skm", MIME_APPLICATION_X_KOAN);
put1("skt", MIME_APPLICATION_X_KOAN);
put1("skd", MIME_APPLICATION_X_KOAN);
put1("skp", MIME_APPLICATION_X_KOAN);
put1("js", MIME_APPLICATION_X_JAVASCRIPT);
put1("hdf", MIME_APPLICATION_X_HDF);
put1("gtar", MIME_APPLICATION_X_GTAR);
put1("spl", MIME_APPLICATION_X_FUTURESPLASH);
put1("dvi", MIME_APPLICATION_X_DVI);
put1("dxr", MIME_APPLICATION_X_DIRECTOR);
put1("dir", MIME_APPLICATION_X_DIRECTOR);
put1("dcr", MIME_APPLICATION_X_DIRECTOR);
put1("csh", MIME_APPLICATION_X_CSH);
put1("cpio", MIME_APPLICATION_X_CPIO);
put1("pgn", MIME_APPLICATION_X_CHESS_PGN);
put1("vcd", MIME_APPLICATION_X_CDLINK);
put1("bcpio", MIME_APPLICATION_X_BCPIO);
put1("rm", MIME_APPLICATION_VND_RNREALMEDIA);
put1("ppt", MIME_APPLICATION_VND_MSPOWERPOINT);
put1("mif", MIME_APPLICATION_VND_MIF);
put1("grxml", MIME_APPLICATION_SRGS_XML);
put1("gram", MIME_APPLICATION_SRGS);
put1("smil", MIME_APPLICATION_RDF_SMIL);
put1("smi", MIME_APPLICATION_RDF_SMIL);
put1("rdf", MIME_APPLICATION_RDF_XML);
put1("ogg", MIME_APPLICATION_X_OGG);
put1("oda", MIME_APPLICATION_ODA);
put1("dmg", MIME_APPLICATION_OCTET_STREAM);
put1("lzh", MIME_APPLICATION_OCTET_STREAM);
put1("so", MIME_APPLICATION_OCTET_STREAM);
put1("lha", MIME_APPLICATION_OCTET_STREAM);
put1("dms", MIME_APPLICATION_OCTET_STREAM);
put1("bin", MIME_APPLICATION_OCTET_STREAM);
put1("mathml", MIME_APPLICATION_MATHML_XML);
put1("cpt", MIME_APPLICATION_MAC_COMPACTPRO);
put1("hqx", MIME_APPLICATION_MAC_BINHEX40);
put1("jnlp", MIME_APPLICATION_JNLP);
put1("ez", MIME_APPLICATION_ANDREW_INSET);
put1("txt", MIME_TEXT_PLAIN);
put1("ini", MIME_TEXT_PLAIN);
put1("c", MIME_TEXT_PLAIN);
put1("h", MIME_TEXT_PLAIN);
put1("cpp", MIME_TEXT_PLAIN);
put1("cxx", MIME_TEXT_PLAIN);
put1("cc", MIME_TEXT_PLAIN);
put1("chh", MIME_TEXT_PLAIN);
put1("java", MIME_TEXT_PLAIN);
put1("csv", MIME_TEXT_PLAIN);
put1("bat", MIME_TEXT_PLAIN);
put1("cmd", MIME_TEXT_PLAIN);
put1("asc", MIME_TEXT_PLAIN);
put1("rtf", MIME_TEXT_RTF);
put1("rtx", MIME_TEXT_RICHTEXT);
put1("html", MIME_TEXT_HTML);
put1("htm", MIME_TEXT_HTML);
put1("zip", MIME_APPLICATION_ZIP);
put1("rar", MIME_APPLICATION_X_RAR_COMPRESSED);
put1("gzip", MIME_APPLICATION_X_GZIP);
put1("gz", MIME_APPLICATION_X_GZIP);
put1("tgz", MIME_APPLICATION_TGZ);
put1("tar", MIME_APPLICATION_X_TAR);
put1("gif", MIME_IMAGE_GIF);
put1("jpeg", MIME_IMAGE_JPEG);
put1("jpg", MIME_IMAGE_JPEG);
put1("jpe", MIME_IMAGE_JPEG);
put1("tiff", MIME_IMAGE_TIFF);
put1("tif", MIME_IMAGE_TIFF);
put1("png", MIME_IMAGE_PNG);
put1("au", MIME_AUDIO_BASIC);
put1("snd", MIME_AUDIO_BASIC);
put1("wav", MIME_AUDIO_X_WAV);
put1("mov", MIME_VIDEO_QUICKTIME);
put1("qt", MIME_VIDEO_QUICKTIME);
put1("mpeg", MIME_VIDEO_MPEG);
put1("mpg", MIME_VIDEO_MPEG);
put1("mpe", MIME_VIDEO_MPEG);
put1("abs", MIME_VIDEO_MPEG);
put1("doc", MIME_APPLICATION_MSWORD);
put1("xls", MIME_APPLICATION_VND_MSEXCEL);
put1("eps", MIME_APPLICATION_POSTSCRIPT);
put1("ai", MIME_APPLICATION_POSTSCRIPT);
put1("ps", MIME_APPLICATION_POSTSCRIPT);
put1("pdf", MIME_APPLICATION_PDF);
put1("exe", MIME_APPLICATION_OCTET_STREAM);
put1("dll", MIME_APPLICATION_OCTET_STREAM);
put1("class", MIME_APPLICATION_OCTET_STREAM);
put1("jar", MIME_APPLICATION_JAVA_ARCHIVE);
}};
}
public static void main(String[] args) {
System.out.println(mimeTypeMapping.size());
}
/**
* Registers MIME type for provided extension. Existing extension type will be overriden.
*/
public static void registerMimeType(String ext, String mimeType) {
mimeTypeMapping.put(ext, mimeType);
}
/**
* Returns the corresponding MIME type to the given extension.
* If no MIME type was found it returns 'application/octet-stream' type.
*/
public static String getMimeType(String ext) {
String mimeType = lookupMimeType(ext);
if (mimeType == null) {
mimeType = MIME_APPLICATION_OCTET_STREAM;
}
return mimeType;
}
/**
* Simply returns MIME type or <code>null</code> if no type is found.
*/
public static String lookupMimeType(String ext) {
return mimeTypeMapping.get(ext.toLowerCase());
}
}
That way you could obtain the extension from the content-type...
To get the file extension You could do:
multipartFile.getOriginalFilename().split("\\.")[1];
The name You get with:
multipartFile.getOriginalFilename().split("\\.")[0];
What if the user upload a executable file with .doc extension? You could get the content type:
multipartFile.getContentType();
This will return a MIME type string.
To get the correct file extension you could search the file name string for the last dot and then split it at this position.
you can use org.springframework.util.StringUtils :
String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());
I solved the issue with splitting on . and taking the last part (not the 2nd),
To get Extension
String[] fileFrags = file.getOriginalFilename().split("\\.")
String extension = fileFrags[fileFrags.length-1]
To get the name
String fileName = file.substring(0,file.lenghth()-fileFrags[fileFrags-1].length()-1)
String extension = FilenameUtils.getExtension(inputFile.getOriginalFilename());
System.out.println("File Extension "+extension);
You can check file extension in this way:
if (file.getContentType() == null
|| !file.getContentType().equals(MediaType.APPLICATION_PDF_VALUE)) {
throw new RuntimeException("Wrong extension!");
}
I have a class
like below
public class SampleReflection {
public static final String TWO_name = "html";
public static final String TWO_find = "css";
public static final String ONE_KEY_java = "java";
public static final String ONE_KEY_jsp = "jsp";
public static final String ONE_KEY_oracle = "oracle";
public static final String ONE_KEY_spring = "spring";
public static final String ONE_KEY_struts = "struts";
}
I would like to get all the fields which starts with ONE_KEY and their value.
because the ONE_KEY_xxx can be of any numbers.
how to do this in java reflection or any other way in java ?
thanks
You can use SampleReflection.class.getDeclaredFields(), iterate over the result and filter by name. Then call field.get(null) to get the value of the static fields. If you want to access non-public fields as well you might have to call first.setAccessible(true) (provided the security manager allows that).
Alternatively you could have a look at Apache Common's reflection utilities, e.g. FieldUtils and the like.
Depending on what you actually want to achieve there might be better approaches though, e.g. using a map, enums etc.
In your case where you have static fields using an enum might be a better way to go.
Example:
enum SampleFields {
TWO_name("html"),
TWO_find("css"),
ONE_KEY_java("java"),
ONE_KEY_jsp("jsp");
ONE_KEY_oracle("oracle"),
...;
private String value;
private SampleFields(String v) {
value = v;
}
}
Then iterate over SampleFields.values() and filter by name.
Alternatively, if that fits your needs, you could split the names and pass a map to the enum values, e.g.
enum SampleFields {
TWO(/*build a map "name"->"html","find"->"css")*/ ),
ONE_KEY(/*build a map "java"->"java","jsp"->"jsp", ...*/);
private Map<String, String> values;
private SampleFields(Map<String, String> map) {
values = map;
}
}
Then get the enum values like this: SampleFields.valueOf("ONE_KEY").get("java")
Thanks for the answer,
this is what i was looking for,
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class SampleReflection {
public static final String TWO_name = "html";
public static final String TWO_find = "css";
public static final String ONE_KEY_java = "java";
public static final String ONE_KEY_jsp = "jsp";
public static final String ONE_KEY_oracle = "oracle";
public static final String ONE_KEY_spring = "spring";
public static final String ONE_KEY_struts = "struts";
public static void main(String[] args) {
Class<?> thisClass = null;
Map<String,String> keyValueMap = new HashMap<String,String>();
try {
thisClass = Class.forName(SampleReflection.class.getName());
Field[] aClassFields = thisClass.getDeclaredFields();
for(Field f : aClassFields){
String fName = f.getName();
if(fName.contains("ONE_KEY")){
keyValueMap.put(fName, (String)f.get(SampleReflection.class));
}
}
for (Map.Entry<String, String> entry : keyValueMap.entrySet())
{
System.out.println(entry.getKey() + "=" + entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}