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);
}
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;
}
}
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;
}
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);
}
}
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;
}
}
Aggregations