Skip to content

Commit

Permalink
Improved MediaType handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
noboomu committed May 14, 2019
1 parent 94b4dd4 commit 13e6ce0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
35 changes: 34 additions & 1 deletion core/src/main/java/io/sinistral/proteus/server/MediaType.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@
*/


import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MediaType
Expand Down Expand Up @@ -1210,6 +1215,11 @@ public static synchronized MediaType getByFileName(String filename)
}
}

public static synchronized MediaType getByMimeType(String type)
{
return Optional.ofNullable(getTypeMap().get(type)).orElse(MediaType.DEFAULT);
}

public String withCharset(String charset)
{
return charset != null ? String.format("%s; charset=%s", this.contentType, charset.toUpperCase()) : this.contentType;
Expand Down Expand Up @@ -1262,6 +1272,30 @@ public String toString()
return this.contentType;
}

private static final Map<String,MediaType> TYPE_MAP = new HashMap<>();

public static Map<String,MediaType> getTypeMap()
{
if(TYPE_MAP.size() == 0) {
Class<?> clazz = MediaType.class;

Field[] fields = clazz.getDeclaredFields();

Arrays.stream(fields).filter(f -> f.getType().equals(MediaType.class)).forEach( f -> {

try
{
MediaType mt = (MediaType)f.get(MediaType.class);
TYPE_MAP.put(mt.contentType,mt);
} catch( Exception e )
{
e.printStackTrace();
}
});
}

return TYPE_MAP;
}

@Override
public int hashCode()
Expand Down Expand Up @@ -1307,5 +1341,4 @@ public String info()

return toString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* @author jbauer
*
*/
public class ServerException extends Exception
public class ServerException extends RuntimeException
{
/**
*
Expand Down

0 comments on commit 13e6ce0

Please sign in to comment.