use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParseException in project tika by apache.
the class YandexTranslator method translate.
@Override
public String translate(String text, String sourceLanguage, String targetLanguage) throws TikaException, IOException {
if (!this.isAvailable()) {
return text;
}
WebClient client = WebClient.create(YANDEX_TRANSLATE_URL_BASE);
String langCode;
if (sourceLanguage == null) {
//Translate Service will identify source language
langCode = targetLanguage;
} else {
//Source language is well known
langCode = sourceLanguage + '-' + targetLanguage;
}
//TODO Add support for text over 10k characters
Response response = client.accept(MediaType.APPLICATION_JSON).query("key", this.apiKey).query("lang", langCode).query("text", text).get();
BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) response.getEntity(), UTF_8));
String line = null;
StringBuffer responseText = new StringBuffer();
while ((line = reader.readLine()) != null) {
responseText.append(line);
}
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonResp = mapper.readTree(responseText.toString());
if (!jsonResp.findValuesAsText("code").isEmpty()) {
String code = jsonResp.findValuesAsText("code").get(0);
if (code.equals("200")) {
return jsonResp.findValue("text").get(0).asText();
} else {
throw new TikaException(jsonResp.findValue("message").get(0).asText());
}
} else {
throw new TikaException("Return message not recognized: " + responseText.toString().substring(0, Math.min(responseText.length(), 100)));
}
} catch (JsonParseException e) {
throw new TikaException("Error requesting translation from '" + sourceLanguage + "' to '" + targetLanguage + "', JSON response from Lingo24 is not well formatted: " + responseText.toString());
}
}
use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParseException in project tika by apache.
the class JoshuaNetworkTranslator method translate.
/**
* <p>Initially then check if the source language has been provided.
* If no source language (or a null value) has been provided then
* we make an attempt to guess the source using Tika's
* {@link org.apache.tika.langdetect.OptimaizeLangDetector}. If we
* are still unable to guess the language then we return the source
* text.</p>
*
* <p>We then process the input text into a new string consisting of
* sentences, one per line e.g. insert \n between the presence of '.'</p>
*
* @see org.apache.tika.language.translate.Translator#translate
* (java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public String translate(String text, String sourceLanguage, String targetLanguage) throws TikaException, IOException {
//create networkURI
if (!networkServer.endsWith("/")) {
networkURI = networkServer + "/" + targetLanguage;
} else {
networkURI = networkServer + targetLanguage;
}
if (!this.isAvailable())
return text;
//make an attempt to guess language if one is not provided.
if (sourceLanguage == null)
sourceLanguage = detectLanguage(text).getLanguage();
//process input text into sentences, one per line
// e.g. insert \n between the presence of '.'
StringBuilder sb = new StringBuilder(text);
int i = 0;
while ((i = sb.indexOf(".", i + 1)) != -1) {
sb.replace(i, i + 1, "\n");
}
String inputText = sb.toString();
WebClient client;
final List<Object> providers = new ArrayList<>();
JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider();
providers.add(jacksonJsonProvider);
client = WebClient.create(networkURI, providers);
ObjectMapper requestMapper = new ObjectMapper();
ObjectNode jsonNode = requestMapper.createObjectNode();
jsonNode.put("inputLanguage", sourceLanguage);
jsonNode.put("inputText", inputText);
//make the reuest
Response response = client.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(jsonNode);
BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) response.getEntity(), UTF_8));
String line;
StringBuilder responseText = new StringBuilder();
while ((line = reader.readLine()) != null) {
responseText.append(line);
}
try {
ObjectMapper responseMapper = new ObjectMapper();
JsonNode jsonResp = responseMapper.readTree(responseText.toString());
if (jsonResp.findValuesAsText("outputText") != null) {
return jsonResp.findValuesAsText("outputText").get(0);
} else {
throw new TikaException(jsonResp.findValue("message").get(0).asText());
}
} catch (JsonParseException e) {
throw new TikaException("Error requesting translation from '" + sourceLanguage + "' to '" + targetLanguage + "', JSON response " + "from Joshua REST Server is not well formatted: " + responseText.toString());
}
}
use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParseException in project bamboobsc by billchen198318.
the class CxfServerBean method shutdownOrReloadCallOneSystem.
@SuppressWarnings("unchecked")
public static Map<String, Object> shutdownOrReloadCallOneSystem(HttpServletRequest request, String system, String type) throws ServiceException, Exception {
if (StringUtils.isBlank(system) || StringUtils.isBlank(type)) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.PARAMS_BLANK));
}
String urlStr = ApplicationSiteUtils.getBasePath(system, request) + "config-services?type=" + type + "&value=" + createParamValue();
logger.info("shutdownOrReloadCallSystem , url=" + urlStr);
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(urlStr);
client.executeMethod(method);
byte[] responseBody = method.getResponseBody();
if (null == responseBody) {
throw new Exception("no response!");
}
String content = new String(responseBody, Constants.BASE_ENCODING);
logger.info("shutdownOrReloadCallSystem , system=" + system + " , type=" + type + " , response=" + content);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> dataMap = null;
try {
dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class);
} catch (JsonParseException e) {
logger.error(e.getMessage().toString());
} catch (JsonMappingException e) {
logger.error(e.getMessage().toString());
}
if (null == dataMap) {
throw new Exception("response content error!");
}
return dataMap;
}
use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParseException in project portal by ixinportal.
the class WeixinUtil method getAccTokenFromWeixin.
/**
* 获得token
*/
public void getAccTokenFromWeixin() {
synchronized (atLock) {
String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}";
try {
Long nowDate = System.currentTimeMillis();
if (ACCESS_TOKEN != null && new Date(nowDate + inDateTime).before(ACCESS_TOKEN.getInDate()))
return;
ByteArrayResource retRes = restTemplate.getForObject(tokenUrl, ByteArrayResource.class, appid, secret);
Map<String, Object> tokenMap = jsonTool.readValue(new String(retRes.getByteArray()), Map.class);
if (tokenMap == null || tokenMap.isEmpty()) {
log.error("微信获取token失败,返回为空");
return;
}
Integer ei = (Integer) tokenMap.get("expires_in");
Date inDate = new Date(nowDate + ei * 1000);
AccToken ACCESS_TOKEN_TMP = new AccToken((String) tokenMap.get("access_token"), inDate);
ACCESS_TOKEN = ACCESS_TOKEN_TMP;
} catch (RestClientException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParseException in project portal by ixinportal.
the class AuthService method getToken.
// @Autowired
// private static RealNameAuthenticationSerivceImpl authenticationSerivceImpl = new RealNameAuthenticationSerivceImpl();
/**
* 获得token
* 访问其他接口的时候 在头信息增加 Authorization :bear+token bear和token之间加个空格
*/
private static String getToken() {
// client_secret:43b484748d3a936330bc50da70d6ce69e1dfef90
try {
// RealNameAuthentication realNameAuthentication = authenticationSerivceImpl.getRealNameAuthenticationExample(new RealNameAuthenticationExample());
long nowDate = System.currentTimeMillis();
if (ACCESS_TOKEN != null && new Date(nowDate + inDateTime).before(inDate)) {
return ACCESS_TOKEN;
}
RealNameAuthentication realNameAuthentication = CacheCustomer.getAUTH_CONFIG_MAP().get(2);
if (realNameAuthentication == null) {
List<RealNameAuthentication> list = SpringContextHolder.getBean(SqlSession.class).selectList("com.itrus.portal.db.RealNameAuthenticationMapper.selectByExample", new RealNameAuthenticationExample());
if (list == null || list.isEmpty()) {
return null;
}
for (RealNameAuthentication nameAuthentication : list) {
if (nameAuthentication.getType() == 2)
realNameAuthentication = nameAuthentication;
}
if (realNameAuthentication == null) {
return null;
}
}
Map params = new HashMap();
params.put("grant_type", "client_credentials");
params.put("client_id", realNameAuthentication.getIdCode());
params.put("client_secret", realNameAuthentication.getKeyCode());
String rep = HttpClientUtil.postForm(realNameAuthentication.getAccessTokenaddress() + TOKEN, null, params);
// System.out.println("AuthService getToken()_rep : " + rep);
JSONObject data = JSON.parseObject(rep);
ACCESS_TOKEN = data.getString("access_token");
inDate = new Date(nowDate + data.getLongValue("expires_in"));
return ACCESS_TOKEN;
} catch (RestClientException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Aggregations