Search in sources :

Example 11 with JsonParseException

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());
    }
}
Also used : Response(javax.ws.rs.core.Response) TikaException(org.apache.tika.exception.TikaException) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonParseException(com.fasterxml.jackson.core.JsonParseException) WebClient(org.apache.cxf.jaxrs.client.WebClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 12 with JsonParseException

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());
    }
}
Also used : TikaException(org.apache.tika.exception.TikaException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonParseException(com.fasterxml.jackson.core.JsonParseException) WebClient(org.apache.cxf.jaxrs.client.WebClient) Response(javax.ws.rs.core.Response) BufferedReader(java.io.BufferedReader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 13 with JsonParseException

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;
}
Also used : ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) HttpClient(org.apache.commons.httpclient.HttpClient) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JsonParseException(com.fasterxml.jackson.core.JsonParseException) HttpMethod(org.apache.commons.httpclient.HttpMethod) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 14 with JsonParseException

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();
        }
    }
}
Also used : JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) RestClientException(org.springframework.web.client.RestClientException) ByteArrayResource(org.springframework.core.io.ByteArrayResource) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Date(java.util.Date)

Example 15 with JsonParseException

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;
}
Also used : SqlSession(org.apache.ibatis.session.SqlSession) HashMap(java.util.HashMap) IOException(java.io.IOException) RealNameAuthentication(com.itrus.portal.db.RealNameAuthentication) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Date(java.util.Date) RestClientException(org.springframework.web.client.RestClientException) IOException(java.io.IOException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) RealNameAuthenticationExample(com.itrus.portal.db.RealNameAuthenticationExample) JSONObject(com.alibaba.fastjson.JSONObject) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) RestClientException(org.springframework.web.client.RestClientException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

JsonParseException (com.fasterxml.jackson.core.JsonParseException)145 IOException (java.io.IOException)75 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)58 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)36 JsonParser (com.fasterxml.jackson.core.JsonParser)23 JsonNode (com.fasterxml.jackson.databind.JsonNode)20 Map (java.util.Map)19 JsonToken (com.fasterxml.jackson.core.JsonToken)15 InputStream (java.io.InputStream)15 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)14 HashMap (java.util.HashMap)12 File (java.io.File)11 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)9 JsonFactory (com.fasterxml.jackson.core.JsonFactory)7 JsonLocation (com.fasterxml.jackson.core.JsonLocation)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 InputStreamReader (java.io.InputStreamReader)5 Date (java.util.Date)5 GZIPInputStream (java.util.zip.GZIPInputStream)5