Search in sources :

Example 46 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project motech by motech.

the class EditableLookupsLoader method loadEntitiesLookups.

private List<EntityLookups> loadEntitiesLookups(Bundle bundle) {
    URL lookupsResource = getLookupsResource(bundle);
    if (lookupsResource == null) {
        return new ArrayList<>();
    }
    try (InputStream stream = lookupsResource.openStream()) {
        String lookupsJson = toLookupsJson(bundle, stream);
        List<EntityLookups> entitiesLookups = new ArrayList<>();
        if (!StringUtils.isBlank(lookupsJson)) {
            entitiesLookups.addAll(Arrays.asList(GSON.fromJson(lookupsJson, EntityLookups[].class)));
        }
        return entitiesLookups;
    } catch (JsonSyntaxException e) {
        throw new MalformedLookupsJsonException(bundle.getSymbolicName(), e);
    } catch (IOException e) {
        throw new LookupsJsonReadException(bundle.getSymbolicName(), e);
    }
}
Also used : MalformedLookupsJsonException(org.motechproject.mds.exception.loader.MalformedLookupsJsonException) JsonSyntaxException(com.google.gson.JsonSyntaxException) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) LookupsJsonReadException(org.motechproject.mds.exception.loader.LookupsJsonReadException) URL(java.net.URL) EntityLookups(org.motechproject.mds.lookup.EntityLookups)

Example 47 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project leshan by eclipse.

the class ClientServlet method extractLwM2mNode.

private LwM2mNode extractLwM2mNode(String target, HttpServletRequest req) throws IOException {
    String contentType = StringUtils.substringBefore(req.getContentType(), ";");
    if ("application/json".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
        LwM2mNode node;
        try {
            node = gson.fromJson(content, LwM2mNode.class);
        } catch (JsonSyntaxException e) {
            throw new InvalidRequestException(e, "unable to parse json to tlv:%s", e.getMessage());
        }
        return node;
    } else if ("text/plain".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
        int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1));
        return LwM2mSingleResource.newStringResource(rscId, content);
    }
    throw new InvalidRequestException("content type %s not supported", req.getContentType());
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) InvalidRequestException(org.eclipse.leshan.core.request.exception.InvalidRequestException) LwM2mNode(org.eclipse.leshan.core.node.LwM2mNode)

Example 48 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project leshan by eclipse.

the class BootstrapServlet method doPost.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (req.getPathInfo() == null) {
        // we need the endpoint in the URL
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "endpoint name should be specified in the URL");
        return;
    }
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    // endPoint
    if (path.length != 1) {
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "endpoint name should be specified in the URL, nothing more");
        return;
    }
    String endpoint = path[0];
    try {
        BootstrapConfig cfg = gson.fromJson(new InputStreamReader(req.getInputStream()), BootstrapConfig.class);
        if (cfg == null) {
            sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "no content");
        } else {
            bsStore.addConfig(endpoint, cfg);
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    } catch (JsonSyntaxException | ConfigurationException e) {
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) InputStreamReader(java.io.InputStreamReader) ConfigurationException(org.eclipse.leshan.server.bootstrap.demo.ConfigurationChecker.ConfigurationException) BootstrapConfig(org.eclipse.leshan.server.bootstrap.BootstrapConfig)

Example 49 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project opencast by opencast.

the class AnimateServiceRestEndpoint method animate.

@POST
@Produces(MediaType.TEXT_XML)
@Path("animate")
@RestQuery(name = "animate", description = "Create animates video clip", restParameters = { @RestParameter(name = "animation", isRequired = true, type = STRING, description = "Location of to the animation"), @RestParameter(name = "arguments", isRequired = true, type = STRING, description = "Synfig command line arguments as JSON array"), @RestParameter(name = "metadata", isRequired = true, type = STRING, description = "Metadata for replacement as JSON object") }, reponses = { @RestResponse(description = "Animation created successfully", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "Invalid data", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "Internal error", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "Returns the path to the generated animation video")
public Response animate(@FormParam("animation") String animation, @FormParam("arguments") String argumentsString, @FormParam("metadata") String metadataString) {
    Gson gson = new Gson();
    try {
        Map<String, String> metadata = gson.fromJson(metadataString, stringMapType);
        List<String> arguments = gson.fromJson(argumentsString, stringListType);
        logger.debug("Start animation");
        Job job = animateService.animate(new URI(animation), metadata, arguments);
        return Response.ok(new JaxbJob(job)).build();
    } catch (JsonSyntaxException | URISyntaxException | NullPointerException e) {
        logger.debug("Invalid data passed to REST endpoint:\nanimation: {}\nmetadata: {}\narguments: {})", animation, metadataString, argumentsString);
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (AnimateServiceException e) {
        logger.error("Error animating file {}", animation, e);
        return Response.serverError().build();
    }
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) AnimateServiceException(org.opencastproject.animate.api.AnimateServiceException) JaxbJob(org.opencastproject.job.api.JaxbJob) Gson(com.google.gson.Gson) URISyntaxException(java.net.URISyntaxException) JaxbJob(org.opencastproject.job.api.JaxbJob) Job(org.opencastproject.job.api.Job) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 50 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project opencast by opencast.

the class CaptureAgentStateRestService method setConfiguration.

@POST
@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_JSON })
@Path("agents/{name}/configuration")
@RestQuery(name = "setAgentStateConfiguration", description = "Set the configuration of a given capture agent, registering it if it does not exist", pathParameters = { @RestParameter(description = "Name of the capture agent", isRequired = true, name = "name", type = Type.STRING) }, restParameters = { @RestParameter(description = "An XML or JSON representation of the capabilities. XML as specified in " + "http://java.sun.com/dtd/properties.dtd (friendly names as keys, device locations as corresponding values)", type = Type.TEXT, isRequired = true, name = "configuration") }, reponses = { @RestResponse(description = "An XML or JSON representation of the agent configuration", responseCode = SC_OK), @RestResponse(description = "The configuration format is incorrect OR the agent name is blank or null", responseCode = SC_BAD_REQUEST) }, returnDescription = "")
public Response setConfiguration(@PathParam("name") String agentName, @FormParam("configuration") String configuration) {
    if (service == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).build();
    if (StringUtils.isBlank(configuration)) {
        logger.debug("The configuration data cannot be blank");
        return Response.serverError().status(Response.Status.BAD_REQUEST).build();
    }
    Properties caps;
    if (StringUtils.startsWith(configuration, "{")) {
        // JSON
        Gson gson = new Gson();
        try {
            caps = gson.fromJson(configuration, Properties.class);
            if (!service.setAgentConfiguration(agentName, caps)) {
                logger.debug("'{}''s configuration has not been updated because nothing has been changed", agentName);
            }
            return Response.ok(gson.toJson(caps)).type(MediaType.APPLICATION_JSON).build();
        } catch (JsonSyntaxException e) {
            logger.debug("Exception when deserializing capabilities: {}", e.getMessage());
            return Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build();
        }
    } else {
        // XML
        caps = new Properties();
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(configuration.getBytes());
            caps.loadFromXML(bais);
            if (!service.setAgentConfiguration(agentName, caps)) {
                logger.debug("'{}''s configuration has not been updated because nothing has been changed", agentName);
            }
            // Prepares the value to return
            PropertiesResponse r = new PropertiesResponse(caps);
            logger.debug("{}'s configuration updated", agentName);
            return Response.ok(r).type(MediaType.TEXT_XML).build();
        } catch (IOException e) {
            logger.debug("Unexpected I/O Exception when unmarshalling the capabilities: {}", e.getMessage());
            return Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build();
        } finally {
            IOUtils.closeQuietly(bais);
        }
    }
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) PropertiesResponse(org.opencastproject.util.PropertiesResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) Gson(com.google.gson.Gson) IOException(java.io.IOException) Properties(java.util.Properties) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

JsonSyntaxException (com.google.gson.JsonSyntaxException)379 Gson (com.google.gson.Gson)169 IOException (java.io.IOException)83 HashMap (java.util.HashMap)68 JsonElement (com.google.gson.JsonElement)62 JsonObject (com.google.gson.JsonObject)58 ArrayList (java.util.ArrayList)46 JsonParser (com.google.gson.JsonParser)42 GsonBuilder (com.google.gson.GsonBuilder)38 Cursor (android.database.Cursor)33 InputStreamReader (java.io.InputStreamReader)30 Map (java.util.Map)30 BadRequestException (co.cask.cdap.common.BadRequestException)28 JsonArray (com.google.gson.JsonArray)28 Path (javax.ws.rs.Path)28 Reader (java.io.Reader)26 Type (java.lang.reflect.Type)23 JsonIOException (com.google.gson.JsonIOException)21 FileReader (java.io.FileReader)21 File (java.io.File)19