Search in sources :

Example 86 with JsonParseException

use of com.google.gson.JsonParseException in project cloudstack by apache.

the class VolumeApiServiceImpl method updateMissingRootDiskController.

public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) {
    if (vm == null || !VirtualMachine.Type.User.equals(vm.getType()) || StringUtils.isEmpty(rootVolChainInfo)) {
        return;
    }
    String rootDiskController = null;
    try {
        final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class);
        if (infoInChain != null) {
            rootDiskController = infoInChain.getControllerFromDeviceBusName();
        }
        final UserVmVO userVmVo = _userVmDao.findById(vm.getId());
        if ((rootDiskController != null) && (!rootDiskController.isEmpty())) {
            _userVmDao.loadDetails(userVmVo);
            _userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController);
        }
    } catch (JsonParseException e) {
        s_logger.debug("Error parsing chain info json: " + e.getMessage());
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) VirtualMachineDiskInfo(org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo) JsonParseException(com.google.gson.JsonParseException)

Example 87 with JsonParseException

use of com.google.gson.JsonParseException in project AgriCraft by AgriCraft.

the class AgriPlantIngredientSerializer method parse.

@Nonnull
@Override
public AgriPlantIngredient parse(JsonObject json) {
    if (!json.has("plant")) {
        throw new JsonParseException("Agricraft plant ingredient must have a \"plant\" property!");
    }
    String id = json.get("plant").getAsString();
    IAgriPlant plant = AgriApi.getPlantRegistry().get(id).orElse(AgriApi.getPlantRegistry().getNoPlant());
    if (plant.isPlant()) {
        return new AgriPlantIngredient(plant);
    } else {
        return new AgriLazyPlantIngredient(id);
    }
}
Also used : AgriPlantIngredient(com.infinityraider.agricraft.api.v1.plant.AgriPlantIngredient) IAgriPlant(com.infinityraider.agricraft.api.v1.plant.IAgriPlant) JsonParseException(com.google.gson.JsonParseException) Nonnull(javax.annotation.Nonnull)

Example 88 with JsonParseException

use of com.google.gson.JsonParseException in project gocd by gocd.

the class ConfigurationPropertyRepresenter method fromJSONHandlingEncryption.

/**
 * Like {@link #fromJSON(JsonReader)}, but handles an additional `secure` flag.
 * <p>
 * Behavior:
 * <p>
 * 1. if `encrypted_value` is provided, it behaves like {@link #fromJSON(JsonReader)} and ignores `secure`
 * 2. only if `value` and `secure` are present, conditionally encrypts `value` => `encrypted_value` depending
 * on the `secure` flag: `true` causes encryption, `false` leaves as plaintext.
 *
 * @param jsonReader a reader for the serialized JSON input
 * @return a {@link ConfigurationProperty}
 */
public static ConfigurationProperty fromJSONHandlingEncryption(JsonReader jsonReader) {
    try {
        final String key = jsonReader.getString("key");
        final String value = jsonReader.optString("value").orElse(null);
        final String encryptedValue = jsonReader.optString("encrypted_value").orElse(null);
        final Boolean isSecure = jsonReader.optBoolean("secure").orElse(null);
        final ConfigurationProperty property = new ConfigurationProperty().deserialize(key, value, encryptedValue);
        if (isBlank(encryptedValue) && null != isSecure) {
            // handle encryptions
            property.handleSecureValueConfiguration(isSecure);
        }
        return property;
    } catch (Exception e) {
        throw new JsonParseException("Could not parse configuration property");
    }
}
Also used : ConfigurationProperty(com.thoughtworks.go.domain.config.ConfigurationProperty) JsonParseException(com.google.gson.JsonParseException) JsonParseException(com.google.gson.JsonParseException)

Example 89 with JsonParseException

use of com.google.gson.JsonParseException in project fc-java-sdk by aliyun.

the class AbstractResponseConsumer method getFcHttpResponse.

/**
 * Convert apache HttpResponse to FC HttpResponse
 * @return
 */
public com.aliyuncs.fc.http.HttpResponse getFcHttpResponse() throws Exception {
    com.aliyuncs.fc.http.HttpResponse response = new com.aliyuncs.fc.http.HttpResponse();
    // Status
    response.setStatus(httpResponse.getStatusLine().getStatusCode());
    // Headers
    Header[] headers = httpResponse.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        Header header = headers[i];
        response.setHeader(header.getName(), header.getValue());
    }
    // Content
    try {
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            InputStream in = entity.getContent();
            response.setContent(IOUtils.toByteArray(in));
        }
        closeResponse(httpResponse);
    } catch (IOException e) {
        throw new ClientException("SDK.ServerUnreachable", "Server unreachable: " + e.toString());
    }
    if (response.getStatus() >= 500) {
        String requestId = response.getHeader(HeaderKeys.REQUEST_ID);
        String stringContent = response.getContent() == null ? "" : FcUtil.toDefaultCharset(response.getContent());
        ServerException se;
        try {
            se = new Gson().fromJson(stringContent, ServerException.class);
        } catch (JsonParseException e) {
            se = new ServerException("InternalServiceError", "Failed to parse response content", requestId);
        }
        se.setStatusCode(response.getStatus());
        se.setRequestId(requestId);
        throw se;
    } else if (response.getStatus() >= 300) {
        ClientException ce;
        if (response.getContent() == null) {
            ce = new ClientException("SDK.ServerUnreachable", "Failed to get response content from server");
        } else {
            try {
                ce = new Gson().fromJson(FcUtil.toDefaultCharset(response.getContent()), ClientException.class);
            } catch (JsonParseException e) {
                ce = new ClientException("SDK.ResponseNotParsable", "Failed to parse response content", e);
            }
        }
        if (ce == null) {
            ce = new ClientException("SDK.UnknownError", "Unknown client error");
        }
        ce.setStatusCode(response.getStatus());
        ce.setRequestId(response.getHeader(HeaderKeys.REQUEST_ID));
        throw ce;
    }
    return response;
}
Also used : ServerException(com.aliyuncs.fc.exceptions.ServerException) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) Gson(com.google.gson.Gson) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) Header(org.apache.http.Header) ClientException(com.aliyuncs.fc.exceptions.ClientException)

Example 90 with JsonParseException

use of com.google.gson.JsonParseException in project SSM by Intel-bigdata.

the class ZeppelinHubRealm method authenticateUser.

/**
 * Send to ZeppelinHub a login request based on the request body which is a JSON that contains 2
 * fields "login" and "password".
 *
 * @param requestBody JSON string of ZeppelinHub payload.
 * @return Account object with login, name (if set in ZeppelinHub), and mail.
 * @throws AuthenticationException if fail to login.
 */
protected User authenticateUser(String requestBody) {
    PutMethod put = new PutMethod(Joiner.on("/").join(zeppelinhubUrl, USER_LOGIN_API_ENDPOINT));
    String responseBody = StringUtils.EMPTY;
    String userSession = StringUtils.EMPTY;
    try {
        put.setRequestEntity(new StringRequestEntity(requestBody, JSON_CONTENT_TYPE, UTF_8_ENCODING));
        int statusCode = httpClient.executeMethod(put);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Cannot login user, HTTP status code is {} instead on 200 (OK)", statusCode);
            put.releaseConnection();
            throw new AuthenticationException("Couldnt login to ZeppelinHub. " + "Login or password incorrect");
        }
        responseBody = put.getResponseBodyAsString();
        userSession = put.getResponseHeader(USER_SESSION_HEADER).getValue();
        put.releaseConnection();
    } catch (IOException e) {
        LOG.error("Cannot login user", e);
        throw new AuthenticationException(e.getMessage());
    }
    User account = null;
    try {
        account = gson.fromJson(responseBody, User.class);
    } catch (JsonParseException e) {
        LOG.error("Cannot deserialize ZeppelinHub response to User instance", e);
        throw new AuthenticationException("Cannot login to ZeppelinHub");
    }
    onLoginSuccess(account.login, userSession);
    return account;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) AuthenticationException(org.apache.shiro.authc.AuthenticationException) PutMethod(org.apache.commons.httpclient.methods.PutMethod) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException)

Aggregations

JsonParseException (com.google.gson.JsonParseException)267 JsonObject (com.google.gson.JsonObject)105 IOException (java.io.IOException)78 JsonElement (com.google.gson.JsonElement)71 Gson (com.google.gson.Gson)39 JsonArray (com.google.gson.JsonArray)30 JsonReader (com.google.gson.stream.JsonReader)28 InputStreamReader (java.io.InputStreamReader)28 JsonParser (com.google.gson.JsonParser)25 JsonPrimitive (com.google.gson.JsonPrimitive)25 Map (java.util.Map)25 InputStream (java.io.InputStream)23 GsonBuilder (com.google.gson.GsonBuilder)20 ArrayList (java.util.ArrayList)20 Type (java.lang.reflect.Type)17 JsonWriter (com.google.gson.stream.JsonWriter)15 StringReader (java.io.StringReader)13 HashMap (java.util.HashMap)13 LinkedHashMap (java.util.LinkedHashMap)13 HttpUrl (okhttp3.HttpUrl)13