Search in sources :

Example 61 with JsonParseException

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

the class AnalyzerManager method newInstance.

public static AnalyzerManager newInstance(int maxTokens) throws IOException {
    InputStream is = AnalyzerManager.class.getClassLoader().getResourceAsStream("lucene-analyzers.json");
    Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeHierarchyAdapter(Map.class, new AnalyzerDeserializer(maxTokens));
    Gson gson = builder.create();
    Map<String, Analyzer> map = gson.fromJson(reader, Map.class);
    Analyzer general = map.get(GENERAL);
    Analyzer alphaIdeo = map.get(ALPHA_IDEOGRAPH);
    Analyzer common = map.get(COMMON_TOKENS);
    if (general == null) {
        throw new JsonParseException("Must specify " + GENERAL + " analyzer");
    }
    if (common == null) {
        throw new JsonParseException("Must specify " + COMMON_TOKENS + " analyzer");
    }
    return new AnalyzerManager(general, common);
}
Also used : InputStreamReader(java.io.InputStreamReader) GsonBuilder(com.google.gson.GsonBuilder) InputStream(java.io.InputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) Analyzer(org.apache.lucene.analysis.Analyzer) JsonParseException(com.google.gson.JsonParseException)

Example 62 with JsonParseException

use of com.google.gson.JsonParseException in project cdap by caskdata.

the class ArtifactHttpHandler method addArtifact.

@POST
@Path("/namespaces/{namespace-id}/artifacts/{artifact-name}")
@AuditPolicy(AuditDetail.HEADERS)
public BodyConsumer addArtifact(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") final String namespaceId, @PathParam("artifact-name") final String artifactName, @HeaderParam(VERSION_HEADER) final String artifactVersion, @HeaderParam(EXTENDS_HEADER) final String parentArtifactsStr, @HeaderParam(PLUGINS_HEADER) String pluginClasses) throws NamespaceNotFoundException, BadRequestException {
    final NamespaceId namespace = validateAndGetNamespace(namespaceId);
    // and validated there
    if (artifactVersion != null && !artifactVersion.isEmpty()) {
        validateAndGetArtifactId(namespace, artifactName, artifactVersion);
    }
    final Set<ArtifactRange> parentArtifacts = parseExtendsHeader(namespace, parentArtifactsStr);
    final Set<PluginClass> additionalPluginClasses;
    if (pluginClasses == null) {
        additionalPluginClasses = ImmutableSet.of();
    } else {
        try {
            additionalPluginClasses = GSON.fromJson(pluginClasses, PLUGINS_TYPE);
        } catch (JsonParseException e) {
            responder.sendString(HttpResponseStatus.BAD_REQUEST, String.format("%s header '%s' is invalid: %s", PLUGINS_HEADER, pluginClasses, e.getMessage()));
            return null;
        }
    }
    try {
        // copy the artifact contents to local tmp directory
        final File destination = File.createTempFile("artifact-", ".jar", tmpDir);
        return new AbstractBodyConsumer(destination) {

            @Override
            protected void onFinish(HttpResponder responder, File uploadedFile) {
                try {
                    String version = (artifactVersion == null || artifactVersion.isEmpty()) ? getBundleVersion(uploadedFile) : artifactVersion;
                    Id.Artifact artifactId = validateAndGetArtifactId(namespace, artifactName, version);
                    // add the artifact to the repo
                    artifactRepository.addArtifact(artifactId, uploadedFile, parentArtifacts, additionalPluginClasses);
                    responder.sendString(HttpResponseStatus.OK, "Artifact added successfully");
                } catch (ArtifactRangeNotFoundException e) {
                    responder.sendString(HttpResponseStatus.NOT_FOUND, e.getMessage());
                } catch (ArtifactAlreadyExistsException e) {
                    responder.sendString(HttpResponseStatus.CONFLICT, e.getMessage());
                } catch (WriteConflictException e) {
                    responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Conflict while writing artifact, please try again.");
                } catch (IOException e) {
                    LOG.error("Exception while trying to write artifact {}-{}-{}.", namespaceId, artifactName, artifactVersion, e);
                    responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Error performing IO while writing artifact.");
                } catch (BadRequestException e) {
                    responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage());
                } catch (UnauthorizedException e) {
                    responder.sendString(HttpResponseStatus.FORBIDDEN, e.getMessage());
                } catch (Exception e) {
                    LOG.error("Error while writing artifact {}-{}-{}", namespaceId, artifactName, artifactVersion, e);
                    responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Error while adding artifact.");
                }
            }

            private String getBundleVersion(File file) throws BadRequestException, IOException {
                try (JarFile jarFile = new JarFile(file)) {
                    Manifest manifest = jarFile.getManifest();
                    if (manifest == null) {
                        throw new BadRequestException("Unable to derive version from artifact because it does not contain a manifest. " + "Please package the jar with a manifest, or explicitly specify the artifact version.");
                    }
                    Attributes attributes = manifest.getMainAttributes();
                    String version = attributes == null ? null : attributes.getValue(ManifestFields.BUNDLE_VERSION);
                    if (version == null) {
                        throw new BadRequestException("Unable to derive version from artifact because manifest does not contain Bundle-Version attribute. " + "Please include Bundle-Version in the manifest, or explicitly specify the artifact version.");
                    }
                    return version;
                } catch (ZipException e) {
                    throw new BadRequestException("Artifact is not in zip format. Please make sure it is a jar file.");
                }
            }
        };
    } catch (IOException e) {
        LOG.error("Exception creating temp file to place artifact {} contents", artifactName, e);
        responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Server error creating temp file for artifact.");
        return null;
    }
}
Also used : ArtifactRangeNotFoundException(co.cask.cdap.common.ArtifactRangeNotFoundException) HttpResponder(co.cask.http.HttpResponder) ArtifactRange(co.cask.cdap.api.artifact.ArtifactRange) Attributes(java.util.jar.Attributes) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) JarFile(java.util.jar.JarFile) Manifest(java.util.jar.Manifest) InvalidArtifactRangeException(co.cask.cdap.api.artifact.InvalidArtifactRangeException) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) ArtifactNotFoundException(co.cask.cdap.common.ArtifactNotFoundException) ZipException(java.util.zip.ZipException) ArtifactAlreadyExistsException(co.cask.cdap.common.ArtifactAlreadyExistsException) InvocationTargetException(java.lang.reflect.InvocationTargetException) BadRequestException(co.cask.cdap.common.BadRequestException) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) JsonParseException(com.google.gson.JsonParseException) PluginNotExistsException(co.cask.cdap.internal.app.runtime.plugin.PluginNotExistsException) ArtifactRangeNotFoundException(co.cask.cdap.common.ArtifactRangeNotFoundException) WriteConflictException(co.cask.cdap.internal.app.runtime.artifact.WriteConflictException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) NotFoundException(co.cask.cdap.common.NotFoundException) ArtifactAlreadyExistsException(co.cask.cdap.common.ArtifactAlreadyExistsException) AbstractBodyConsumer(co.cask.cdap.common.http.AbstractBodyConsumer) WriteConflictException(co.cask.cdap.internal.app.runtime.artifact.WriteConflictException) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) BadRequestException(co.cask.cdap.common.BadRequestException) NamespaceId(co.cask.cdap.proto.id.NamespaceId) Id(co.cask.cdap.proto.Id) ArtifactId(co.cask.cdap.proto.id.ArtifactId) NamespaceId(co.cask.cdap.proto.id.NamespaceId) PluginClass(co.cask.cdap.api.plugin.PluginClass) JarFile(java.util.jar.JarFile) File(java.io.File) Path(javax.ws.rs.Path) AuditPolicy(co.cask.cdap.common.security.AuditPolicy) POST(javax.ws.rs.POST)

Example 63 with JsonParseException

use of com.google.gson.JsonParseException in project SmartCampus by Vegen.

the class RetrofitFactory method getGsonConverterFactory.

public static Converter.Factory getGsonConverterFactory() {
    if (gsonConverterFactory == null) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerTypeAdapter()).registerTypeAdapter(Double.class, new DoubleTypeAdapter()).registerTypeAdapter(Float.class, new FloatTypeAdapter()).registerTypeAdapter(int.class, new IntegerTypeAdapter()).registerTypeAdapter(float.class, new FloatTypeAdapter()).registerTypeAdapter(double.class, new DoubleTypeAdapter()).registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                String value = json.getAsString();
                if (TextUtils.isEmpty(value)) {
                    return null;
                }
                try {
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        gsonConverterFactory = GsonConverterFactory.create(gson);
    }
    return gsonConverterFactory;
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) JsonParseException(com.google.gson.JsonParseException) Date(java.util.Date) Type(java.lang.reflect.Type) JsonDeserializationContext(com.google.gson.JsonDeserializationContext) JsonElement(com.google.gson.JsonElement) JsonParseException(com.google.gson.JsonParseException) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 64 with JsonParseException

use of com.google.gson.JsonParseException in project Gaspunk by Ladysnake.

the class SpecialRewardChecker method retrieveSpecialRewards.

/**
 * Populates <code>specialPersons</code> with entries from our page of people having won special rewards
 */
public static void retrieveSpecialRewards() {
    try {
        Gson GSON = new Gson();
        URLConnection rewardPage = new URL("https://ladysnake.glitch.me/gaspunk/users").openConnection();
        rewardPage.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(rewardPage.getInputStream()));
        String inputLine;
        StringBuilder jsonString = new StringBuilder();
        while ((inputLine = in.readLine()) != null) jsonString.append(inputLine);
        in.close();
        Type listType = new TypeToken<Map<String, List<String>>>() {
        }.getType();
        Map<String, List<String>> uuidList = GSON.fromJson(jsonString.toString(), listType);
        specialPersons = uuidList.entrySet().stream().map(SpecialRewardChecker::deserializeEntry).filter(// remove invalid entries
        Objects::nonNull).collect(ImmutableMap.toImmutableMap(Pair::getKey, Pair::getValue));
        GasPunk.proxy.onSpecialRewardsRetrieved();
    } catch (IOException e) {
        GasPunk.LOGGER.warn("Could not connect to LadySnake's reward page. Maybe you're offline ?", e);
    } catch (JsonParseException e) {
        GasPunk.LOGGER.error("Bad json coming from LadySnake's reward page. This should be reported.", e);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) Gson(com.google.gson.Gson) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) URLConnection(java.net.URLConnection) URL(java.net.URL) Type(java.lang.reflect.Type) BufferedReader(java.io.BufferedReader) ImmutableList(com.google.common.collect.ImmutableList) ImmutableMap(com.google.common.collect.ImmutableMap) Pair(org.apache.commons.lang3.tuple.Pair)

Example 65 with JsonParseException

use of com.google.gson.JsonParseException in project Palm300Heroes by nicolite.

the class ExceptionEngine method handleException.

public static APIException handleException(Throwable throwable) {
    throwable.printStackTrace();
    APIException apiException;
    if (throwable instanceof HttpException) {
        HttpException httpException = (HttpException) throwable;
        apiException = new APIException(throwable, httpException.code());
        apiException.setMsg("网络错误");
        return apiException;
    } else if (throwable instanceof JsonParseException || throwable instanceof JSONException || throwable instanceof ParseException || throwable instanceof MalformedJsonException) {
        apiException = new APIException(throwable, PARSE_SERVER_DATA_ERROR);
        apiException.setMsg("解析数据错误");
        return apiException;
    } else if (throwable instanceof ConnectException) {
        apiException = new APIException(throwable, CONNECT_ERROR);
        apiException.setMsg("网络连接失败");
        return apiException;
    } else if (throwable instanceof SocketTimeoutException) {
        apiException = new APIException(throwable, CONNECT_TIME_OUT_ERROR);
        apiException.setMsg("网络连接超时");
        return apiException;
    } else if (throwable instanceof ServerException) {
        ServerException serverException = (ServerException) throwable;
        apiException = new APIException(serverException, serverException.getCode());
        apiException.setMsg(serverException.getMsg());
        return apiException;
    } else {
        apiException = new APIException(throwable, UN_KNOWN_ERROR);
        apiException.setMsg("未知错误");
        return apiException;
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) JSONException(org.json.JSONException) HttpException(retrofit2.HttpException) JsonParseException(com.google.gson.JsonParseException) ParseException(java.text.ParseException) JsonParseException(com.google.gson.JsonParseException) MalformedJsonException(com.google.gson.stream.MalformedJsonException) ConnectException(java.net.ConnectException)

Aggregations

JsonParseException (com.google.gson.JsonParseException)66 JsonObject (com.google.gson.JsonObject)24 IOException (java.io.IOException)17 JsonElement (com.google.gson.JsonElement)15 Gson (com.google.gson.Gson)14 GsonBuilder (com.google.gson.GsonBuilder)9 Type (java.lang.reflect.Type)9 JsonArray (com.google.gson.JsonArray)7 JsonParser (com.google.gson.JsonParser)6 SocketTimeoutException (java.net.SocketTimeoutException)5 JsonDeserializationContext (com.google.gson.JsonDeserializationContext)4 UnknownHostException (java.net.UnknownHostException)4 ArrayList (java.util.ArrayList)4 Resources (android.content.res.Resources)3 TextView (android.widget.TextView)3 RutgersServerIOException (com.tevinjeffrey.rutgersct.rutgersapi.exceptions.RutgersServerIOException)3 InputStreamReader (java.io.InputStreamReader)3 ParseException (java.text.ParseException)3 Date (java.util.Date)3 ResourceLocation (net.minecraft.util.ResourceLocation)3