Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.example.query;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import java.nio.charset.StandardCharsets;
- public class Serializer {
- public static String urlEncode(String text) {
- try {
- return URLEncoder.encode(text, StandardCharsets.UTF_8.toString());
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException("Should never happen", e);
- }
- }
- public static String buildQuery(Object obj) throws SerializerException {
- StringBuilder result = new StringBuilder();
- for (java.lang.reflect.Field fld : obj.getClass().getFields()) {
- QueryField annot = fld.getAnnotation(QueryField.class);
- if (annot == null) {
- // This field has no "Field" annotation, ignore it.
- continue;
- }
- Object fldVal;
- try {
- fldVal = fld.get(obj);
- } catch (IllegalArgumentException e) {
- throw new RuntimeException("Should never happen", e);
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- throw new SerializerException("Failed to access field "+fld.getName(), e);
- }
- if (fldVal == null) {
- if (annot.required()) {
- throw new SerializerException("Required field is null");
- } else {
- // Ignore optional fields
- continue;
- }
- }
- String valText = urlEncode(fldVal.toString());
- String valName = annot.name();
- if (valName.length() == 0) {
- // No custom name, use field name instead
- valName = fld.getName();
- }
- valName = urlEncode(valName);
- result.append('&').append(valName).append('=').append(valText);
- }
- return result.substring(1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement