Example usage for com.google.gson JsonParseException JsonParseException

List of usage examples for com.google.gson JsonParseException JsonParseException

Introduction

In this page you can find the example usage for com.google.gson JsonParseException JsonParseException.

Prototype

public JsonParseException(Throwable cause) 

Source Link

Document

Creates exception with the specified cause.

Usage

From source file:com.relayrides.pushy.apns.DateAsSecondsSinceEpochTypeAdapter.java

License:Open Source License

@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final Date date;

    if (json.isJsonPrimitive()) {
        date = new Date(json.getAsLong() * 1000);
    } else if (json.isJsonNull()) {
        date = null;//from ww  w .  j av a 2 s. co  m
    } else {
        throw new JsonParseException(
                "Dates represented as seconds since the epoch must either be numbers or null.");
    }

    return date;
}

From source file:com.relayrides.pushy.apns.DateAsTimeSinceEpochTypeAdapter.java

License:Open Source License

@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final Date date;

    if (json.isJsonPrimitive()) {
        date = new Date(this.timeUnit.toMillis(json.getAsLong()));
    } else if (json.isJsonNull()) {
        date = null;//from www .j a  v a 2s . c o  m
    } else {
        throw new JsonParseException(
                "Dates represented as time since the epoch must either be numbers or null.");
    }

    return date;
}

From source file:com.reveldigital.api.util.DateTypeFormatter.java

License:Apache License

public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonParseException exception = null;
    final String value = json.getAsString();
    for (DateTimeFormatter format : formats)
        try {//www  . j a  v  a  2s.c om
            synchronized (format) {
                return format.parseDateTime(value).toDate();
            }
        } catch (IllegalArgumentException e) {
            exception = new JsonParseException(e);
        }
    throw exception;
}

From source file:com.ruesga.rview.gerrit.adapters.GerritUtcDateAdapter.java

License:Apache License

@Override
public Date deserialize(JsonElement json, Type typeof, JsonDeserializationContext ctx)
        throws JsonParseException {
    try {/*from   ww w.  j a va 2 s.  c  om*/
        synchronized (mDateFormat) {
            return mDateFormat.parse(json.getAsString());
        }
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}

From source file:com.rw.legion.columncheck.RegexChecker.java

License:Apache License

public RegexChecker(JsonObject json) throws JsonParseException {
    if (!(json.has("regex"))) {
        throw new JsonParseException("RegexChecker requires regex!");
    }//ww  w .j  av  a  2s. c o m

    String regex = json.get("regex").getAsString();
    pattern = Pattern.compile(regex);
}

From source file:com.rw.legion.columntransform.NullReplaceTransformer.java

License:Apache License

public NullReplaceTransformer(JsonObject json) throws JsonParseException {
    if (!(json.has("replacement"))) {
        throw new JsonParseException("NullReplaceTransformer requires " + "replacement string!");
    }//from  w  ww  .jav a 2  s.  c om

    replacement = json.get("replacement").getAsString();
}

From source file:com.rw.legion.DefaultJob.java

License:Apache License

/**
 * Main method./* w w  w  .  ja  va 2 s.  c  o m*/
 * 
 * @param args  Arguments should be: 1) input path, 2) output path, 3)
 * location of Legion objective file.
 */
public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();

    // Load the Legion objective from the JSON doc.
    Path path = new Path(args[2]);
    FileSystem fs = FileSystem.get(new URI(args[2]), conf);
    BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path)));
    String json = "";

    String line = br.readLine();

    while (line != null) {
        json += line;
        line = br.readLine();
    }

    br.close();

    /*
     *  Save the JSON for the Legion objective to the Hadoop configuration,
     *  so we can access it in other containers.
     */
    conf.setStrings("legion_objective", json);

    // De-serialize the objective so we can access the settings here.
    LegionObjective legionObjective = ObjectiveDeserializer.deserialize(json);

    // Start configuring the MapReduce job.
    Job hadoopJob = Job.getInstance(conf, "Legion");

    hadoopJob.setJarByClass(DefaultJob.class);
    hadoopJob.setMapperClass(DefaultMapper.class);
    LazyOutputFormat.setOutputFormatClass(hadoopJob, TextOutputFormat.class);

    // Compress the output to speed things up.
    TextOutputFormat.setCompressOutput(hadoopJob, true);
    TextOutputFormat.setOutputCompressorClass(hadoopJob, GzipCodec.class);

    // What input format do we use?

    try {
        @SuppressWarnings("unchecked")
        Class<? extends FileInputFormat<NullWritable, LegionRecord>> inputClass = (Class<? extends FileInputFormat<NullWritable, LegionRecord>>) Class
                .forName(legionObjective.getInputFormat());

        hadoopJob.setInputFormatClass(inputClass);
    } catch (Exception e) {
        throw new JsonParseException(
                "Problem loading input format " + "class '" + legionObjective.getInputFormat() + "'");
    }

    // Should we set a max combined size?

    if (legionObjective.getMaxCombinedSize() != null) {
        CombineFileInputFormat.setMaxInputSplitSize(hadoopJob, legionObjective.getMaxCombinedSize());
    }

    /* 
     * These are just static convenience methods, so it doesn't matter if
     * they come from the wrong class.
     */
    FileInputFormat.setInputDirRecursive(hadoopJob, true);
    FileInputFormat.addInputPath(hadoopJob, new Path(args[0]));

    FileOutputFormat.setOutputPath(hadoopJob, new Path(args[1]));

    // Since a Legion objective can specify multiple output tables.
    for (OutputTable outputTable : legionObjective.getOutputTables()) {
        MultipleOutputs.addNamedOutput(hadoopJob, outputTable.getTitle(), TextOutputFormat.class,
                NullWritable.class, Text.class);
    }

    MultipleOutputs.addNamedOutput(hadoopJob, "skipped", TextOutputFormat.class, NullWritable.class,
            Text.class);

    hadoopJob.waitForCompletion(true);
}

From source file:com.samebug.clients.search.api.json.AbstractObjectAdapter.java

License:Apache License

@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json == null)
        return null;
    else {//  w  ww . j a  v  a  2s .c  o m
        JsonObject jsonObject = json.getAsJsonObject();
        JsonElement typeFieldValue = jsonObject.get(typeField);
        if (typeFieldValue == null)
            throw new JsonParseException(
                    "Cannot serialize " + typeOfT + " because the type field" + typeField + " is missing");
        else {
            String type = jsonObject.get(typeField).getAsString();

            for (Map.Entry<String, Class<? extends T>> entry : typeClasses.entrySet()) {
                if (entry.getKey().equals(type))
                    return context.deserialize(jsonObject, entry.getValue());
            }
            throw new JsonParseException("Cannot serialize an abstract " + typeOfT + " with the type " + type);
        }
    }
}

From source file:com.sandata.lab.common.utils.data.adapter.CustomJavaDateAdapter.java

License:Open Source License

@Override
public Date deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    try {/*w ww.ja  v a2 s. co  m*/
        return new SimpleDateFormat(dateTimeFormat).parse(jsonElement.getAsString());

    } catch (ParseException e) {

        throw new JsonParseException("Please use the format '" + DateUtil.SANDATA_UTC_DATE_TIME_FORMAT
                + "', for example 2016-10-04T14:30:00Z \n" + e);
    }
}

From source file:com.segment.analytics.gson.Iso8601Utils.java

License:Apache License

/**
 * Parse a date from ISO-8601 formatted string. It expects a format
 * [yyyy-MM-dd|yyyyMMdd][T(hh:mm[:ss[.sss]]|hhmm[ss[.sss]])]?[Z|[+-]hh:mm]]
 *
 * @param date ISO string to parse in the appropriate format.
 * @return the parsed date/* w w  w  .j a va 2 s .co  m*/
 */
static Date parse(String date) throws JsonParseException {
    try {
        int offset = 0;

        // extract year
        int year = parseInt(date, offset, offset += 4);
        if (checkOffset(date, offset, '-')) {
            offset += 1;
        }

        // extract month
        int month = parseInt(date, offset, offset += 2);
        if (checkOffset(date, offset, '-')) {
            offset += 1;
        }

        // extract day
        int day = parseInt(date, offset, offset += 2);
        // default time value
        int hour = 0;
        int minutes = 0;
        int seconds = 0;
        int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time

        // if the value has no time component (and no time zone), we are done
        boolean hasT = checkOffset(date, offset, 'T');

        if (!hasT && (date.length() <= offset)) {
            Calendar calendar = new GregorianCalendar(year, month - 1, day);

            return calendar.getTime();
        }

        if (hasT) {

            // extract hours, minutes, seconds and milliseconds
            hour = parseInt(date, offset += 1, offset += 2);
            if (checkOffset(date, offset, ':')) {
                offset += 1;
            }

            minutes = parseInt(date, offset, offset += 2);
            if (checkOffset(date, offset, ':')) {
                offset += 1;
            }
            // second and milliseconds can be optional
            if (date.length() > offset) {
                char c = date.charAt(offset);
                if (c != 'Z' && c != '+' && c != '-') {
                    seconds = parseInt(date, offset, offset += 2);
                    if (seconds > 59 && seconds < 63)
                        seconds = 59; // truncate up to 3 leap seconds
                    // milliseconds can be optional in the format
                    if (checkOffset(date, offset, '.')) {
                        offset += 1;
                        int endOffset = indexOfNonDigit(date, offset + 1); // assume at least one digit
                        int parseEndOffset = Math.min(endOffset, offset + 3); // parse up to 3 digits
                        int fraction = parseInt(date, offset, parseEndOffset);
                        milliseconds = (int) (Math.pow(10, 3 - (parseEndOffset - offset)) * fraction);
                        offset = endOffset;
                    }
                }
            }
        }

        // extract timezone
        if (date.length() <= offset) {
            throw new IllegalArgumentException("No time zone indicator");
        }

        TimeZone timezone;
        char timezoneIndicator = date.charAt(offset);

        if (timezoneIndicator == 'Z') {
            timezone = TIMEZONE_Z;
        } else if (timezoneIndicator == '+' || timezoneIndicator == '-') {
            String timezoneOffset = date.substring(offset);
            // 18-Jun-2015, tatu: Minor simplification, skip offset of "+0000"/"+00:00"
            if ("+0000".equals(timezoneOffset) || "+00:00".equals(timezoneOffset)) {
                timezone = TIMEZONE_Z;
            } else {
                // 18-Jun-2015, tatu: Looks like offsets only work from GMT, not UTC...
                //    not sure why, but it is what it is.
                String timezoneId = GMT_ID + timezoneOffset;
                timezone = TimeZone.getTimeZone(timezoneId);
                String act = timezone.getID();
                if (!act.equals(timezoneId)) {
                    /* 22-Jan-2015, tatu: Looks like canonical version has colons, but we may be given
                     *    one without. If so, don't sweat.
                     *   Yes, very inefficient. Hopefully not hit often.
                     *   If it becomes a perf problem, add 'loose' comparison instead.
                     */
                    String cleaned = act.replace(":", "");
                    if (!cleaned.equals(timezoneId)) {
                        throw new IndexOutOfBoundsException("Mismatching time zone indicator: " + timezoneId
                                + " given, resolves to " + timezone.getID());
                    }
                }
            }
        } else {
            throw new IndexOutOfBoundsException("Invalid time zone indicator '" + timezoneIndicator + "'");
        }

        Calendar calendar = new GregorianCalendar(timezone);
        calendar.setLenient(false);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);
        calendar.set(Calendar.MILLISECOND, milliseconds);

        return calendar.getTime();
        // If we get a ParseException it'll already have the right message/offset.
        // Other exception types can convert here.
    } catch (IndexOutOfBoundsException | IllegalArgumentException e) {
        throw new JsonParseException("Not an RFC 3339 date: " + date);
    }
}