Search in sources :

Example 71 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project idea-php-typo3-plugin by cedricziel.

the class ComposerUtil method findExtensionKey.

@Nullable
public static String findExtensionKey(@NotNull VirtualFile composerJsonFile) {
    try {
        JsonElement jsonElement = ComposerConfigUtils.parseJson(composerJsonFile);
        if (!isTYPO3ExtensionManifest(jsonElement)) {
            return null;
        }
        // 1.1 find extra.typo3/cms.extension-key
        String extensionKeyFromExtrasTYPO3 = extensionKeyFromExtraExtensionKey(jsonElement);
        if (extensionKeyFromExtrasTYPO3 != null) {
            return extensionKeyFromExtrasTYPO3;
        }
        // 1.2 find extra.installerName
        String extensionKeyFromInstallerName = extensionKeyFromInstallerName(jsonElement);
        if (extensionKeyFromInstallerName != null) {
            return extensionKeyFromInstallerName;
        }
        // 1.3 last resort: package-name
        String extensionKeyFromPackageName = extensionKeyFromPackageName(jsonElement);
        if (extensionKeyFromPackageName != null) {
            return extensionKeyFromPackageName;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JsonSyntaxException | IllegalStateException e) {
    // nothing, yo
    }
    return null;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) JsonElement(com.google.gson.JsonElement) IOException(java.io.IOException) Nullable(org.jetbrains.annotations.Nullable)

Example 72 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project Saiy-PS by brandall76.

the class BingTranslateAPI method execute.

/**
 * Perform a synchronous translation request
 *
 * @param ctx   the application context
 * @param token the Bing OAuth refresh token
 * @param text  the text to be translated
 * @param from  the {@link TranslationLanguageBing} to translate from
 * @param to    the {@link TranslationLanguageBing} to translate to
 * @return a {@link Pair} with the first parameter donating success and the second the result
 */
public Pair<Boolean, String> execute(@NonNull final Context ctx, final String token, final String text, final TranslationLanguageBing from, final TranslationLanguageBing to) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "execute");
    }
    final long then = System.nanoTime();
    final String params;
    try {
        params = PARAM_FROM_LANGUAGE + URLEncoder.encode(from.getLanguage(), ENCODING) + PARAM_TO_LANGUAGE + URLEncoder.encode(to.getLanguage(), ENCODING) + PARAM_TEXT + URLEncoder.encode(text, ENCODING);
    } catch (final UnsupportedEncodingException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "execute: UnsupportedEncodingException");
            e.printStackTrace();
        }
        return new Pair<>(false, null);
    }
    final RequestFuture<String> future = RequestFuture.newFuture();
    final Cache cache = UtilsVolley.getCache(ctx);
    final Network network = new BasicNetwork(new HurlStack());
    final RequestQueue queue = new RequestQueue(cache, network);
    queue.start();
    final String url = SERVICE_URL + params;
    final StringRequest request = new StringRequest(Request.Method.GET, url, future, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(final VolleyError error) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "onErrorResponse: " + error.toString());
                BingTranslateAPI.this.verboseError(error);
            }
            queue.stop();
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            final Map<String, String> params = new HashMap<>();
            params.put("Content-Type", HEADER_CONTENT_TYPE);
            params.put("Accept-Charset", ENCODING);
            params.put("Authorization", "Bearer " + token);
            return params;
        }
    };
    request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(request);
    String translation = "";
    try {
        translation = future.get(THREAD_TIMEOUT, TimeUnit.SECONDS);
    } catch (final InterruptedException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "execute: InterruptedException");
            e.printStackTrace();
        }
    } catch (ExecutionException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "execute: ExecutionException");
            e.printStackTrace();
        }
    } catch (TimeoutException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "execute: TimeoutException");
            e.printStackTrace();
        }
    } finally {
        queue.stop();
    }
    if (DEBUG) {
        MyLog.getElapsed(CLS_NAME, then);
    }
    if (UtilsString.notNaked(translation) && !translation.contains(ARGUMENT_EXCEPTION)) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "translation: " + translation);
        }
        try {
            translation = new GsonBuilder().disableHtmlEscaping().create().fromJson(translation, String.class);
        } catch (final JsonSyntaxException e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "translation: JsonSyntaxException");
                e.printStackTrace();
            }
        }
        return new Pair<>(true, translation);
    } else {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "translation: failed");
        }
        return new Pair<>(false, null);
    }
}
Also used : VolleyError(com.android.volley.VolleyError) HurlStack(com.android.volley.toolbox.HurlStack) HashMap(java.util.HashMap) GsonBuilder(com.google.gson.GsonBuilder) StringRequest(com.android.volley.toolbox.StringRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy) UtilsString(ai.saiy.android.utils.UtilsString) Response(com.android.volley.Response) NetworkResponse(com.android.volley.NetworkResponse) BasicNetwork(com.android.volley.toolbox.BasicNetwork) JsonSyntaxException(com.google.gson.JsonSyntaxException) RequestQueue(com.android.volley.RequestQueue) Network(com.android.volley.Network) BasicNetwork(com.android.volley.toolbox.BasicNetwork) ExecutionException(java.util.concurrent.ExecutionException) Cache(com.android.volley.Cache) TimeoutException(java.util.concurrent.TimeoutException) Pair(android.util.Pair)

Example 73 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project Saiy-PS by brandall76.

the class BingOAuth method execute.

/**
 * Get the Bing OAuth refresh token and store in {@link BingCredentials}
 *
 * @param ctx         the application context
 * @param synchronous whether or not this request should execute synchronously
 * @return true if the process succeeded. False otherwise
 */
public boolean execute(@NonNull final Context ctx, final boolean synchronous) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "execute");
    }
    final long then = System.nanoTime();
    final String encodedSubscriptionKey;
    try {
        encodedSubscriptionKey = URLEncoder.encode(MicrosoftConfiguration.MS_TRANSLATE_SUBSCRIPTION_KEY, ENCODING);
    } catch (final UnsupportedEncodingException e) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "execute: UnsupportedEncodingException");
            e.printStackTrace();
        }
        return false;
    }
    final RequestQueue queue = Volley.newRequestQueue(ctx);
    queue.start();
    Response.Listener<String> listener;
    RequestFuture<String> future = null;
    if (synchronous) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "synchronous: true");
        }
        future = RequestFuture.newFuture();
        listener = future;
    } else {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "synchronous: false");
        }
        listener = new Response.Listener<String>() {

            @Override
            public void onResponse(final String response) {
                if (DEBUG) {
                    MyLog.i(CLS_NAME, "onResponse: " + response);
                }
                queue.stop();
                final BingCredentials credentials = new BingCredentials(response, 600);
                if (DEBUG) {
                    MyLog.i(CLS_NAME, "onResponse: subscription_key: " + credentials.getRefreshToken());
                    MyLog.i(CLS_NAME, "onResponse: expires_in: " + credentials.getExpires());
                }
                SPH.setBingToken(ctx, credentials.getRefreshToken());
                SPH.setBingTokenExpiryTime(ctx, (System.currentTimeMillis() + (credentials.getExpires() * 1000)));
            }
        };
    }
    final StringRequest request = new StringRequest(Request.Method.POST, BING_OAUTH_URL, listener, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(final VolleyError error) {
            if (DEBUG) {
                MyLog.i(CLS_NAME, "onErrorResponse: " + error.toString());
                BingOAuth.this.verboseError(error);
            }
            queue.stop();
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            final Map<String, String> params = new HashMap<>();
            params.put(PARAM_CONTENT_TYPE, HEADER_CONTENT_TYPE);
            params.put(PARAM_ACCEPT_CHARSET, ENCODING);
            params.put(OCP_SUBSCRIPTION_KEY_HEADER, encodedSubscriptionKey);
            return params;
        }
    };
    request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(request);
    String jsonResponse;
    if (synchronous) {
        try {
            jsonResponse = future.get(THREAD_TIMEOUT, TimeUnit.SECONDS);
            final BingCredentials credentials = new BingCredentials(jsonResponse, 600);
            SPH.setBingToken(ctx, credentials.getRefreshToken());
            SPH.setBingTokenExpiryTime(ctx, (System.currentTimeMillis() + (credentials.getExpires() * 1000)));
            if (DEBUG) {
                MyLog.i(CLS_NAME, "onResponse: subscription_key: " + credentials.getRefreshToken());
                MyLog.i(CLS_NAME, "onResponse: expires_in: " + credentials.getExpires());
                MyLog.getElapsed(CLS_NAME, then);
            }
            return true;
        } catch (final JsonSyntaxException e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "execute: JsonSyntaxException");
                e.printStackTrace();
            }
        } catch (final InterruptedException e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "execute: InterruptedException");
                e.printStackTrace();
            }
        } catch (ExecutionException e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "execute: ExecutionException");
                e.printStackTrace();
            }
        } catch (TimeoutException e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "execute: TimeoutException");
                e.printStackTrace();
            }
        } catch (final NullPointerException e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "execute: NullPointerException");
                e.printStackTrace();
            }
        } catch (final Exception e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "execute: Exception");
                e.printStackTrace();
            }
        } finally {
            queue.stop();
        }
    }
    if (DEBUG) {
        MyLog.getElapsed(BingOAuth.class.getSimpleName(), then);
    }
    return false;
}
Also used : VolleyError(com.android.volley.VolleyError) HashMap(java.util.HashMap) StringRequest(com.android.volley.toolbox.StringRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy) TimeoutException(java.util.concurrent.TimeoutException) JsonSyntaxException(com.google.gson.JsonSyntaxException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(com.android.volley.Response) NetworkResponse(com.android.volley.NetworkResponse) JsonSyntaxException(com.google.gson.JsonSyntaxException) RequestQueue(com.android.volley.RequestQueue) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 74 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project Saiy-PS by brandall76.

the class BVCredentials method getLastToken.

/**
 * Method to get the most recent access token stored in the user {@link SPH )
 * shared preferences.
 *
 * @param ctx the application context
 * @return the most recent {@link BVCredentials} object
 */
private static BVCredentials getLastToken(@NonNull final Context ctx) {
    final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    final BVCredentials bvCredentials;
    try {
        bvCredentials = gson.fromJson(SPH.getBeyondVerbalCredentials(ctx), BVCredentials.class);
        if (DEBUG) {
            MyLog.i(CLS_NAME, "getLastToken: " + gson.toJson(bvCredentials));
        }
        return bvCredentials;
    } catch (final JsonSyntaxException e) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "getLastToken: JsonSyntaxException");
            e.printStackTrace();
        }
    } catch (final NullPointerException e) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "getLastToken: NullPointerException");
            e.printStackTrace();
        }
    } catch (final Exception e) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "getLastToken: Exception");
            e.printStackTrace();
        }
    }
    return null;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) JsonSyntaxException(com.google.gson.JsonSyntaxException)

Example 75 with JsonSyntaxException

use of com.google.gson.JsonSyntaxException in project Saiy-PS by brandall76.

the class RecognitionBluemix method onMessage.

@Override
public void onMessage(final String message) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "onMessage: " + message);
    }
    final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    NLUBluemix nluBluemix = null;
    try {
        nluBluemix = gson.fromJson(message, NLUBluemix.class);
    } catch (final JsonSyntaxException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "JsonSyntaxException");
            e.printStackTrace();
        }
    } catch (final NullPointerException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "NullPointerException");
            e.printStackTrace();
        }
    } catch (final Exception e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "Exception");
            e.printStackTrace();
        }
    }
    if (nluBluemix != null) {
        if (UtilsString.notNaked(nluBluemix.getState())) {
            if (DEBUG) {
                MyLog.d(CLS_NAME, "Status message: " + nluBluemix.getState());
            }
        } else {
            partialArray.clear();
            resultsArray.clear();
            confidenceArray.clear();
            bundle.clear();
            final List<Result> results = nluBluemix.getResults();
            if (UtilsList.notNaked(results)) {
                final int resultsSize = results.size();
                if (DEBUG) {
                    MyLog.i(CLS_NAME, "results size: " + resultsSize);
                }
                if (!detectFinal(results)) {
                    if (DEBUG) {
                        MyLog.i(CLS_NAME, "onMessage: have partial");
                    }
                    for (int i = 0; i < resultsSize; i++) {
                        final List<Alternative> alternatives = results.get(i).getAlternatives();
                        final int size = alternatives.size();
                        if (DEBUG) {
                            MyLog.i(CLS_NAME, "partial alternatives size: " + size);
                        }
                        for (int j = 0; j < size; j++) {
                            if (DEBUG) {
                                MyLog.i(CLS_NAME, "final result: " + alternatives.get(j).getTranscript() + " ~ " + alternatives.get(j).getConfidence());
                            }
                            partialArray.add(alternatives.get(j).getTranscript().trim());
                        }
                    }
                    bundle.putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, partialArray);
                    listener.onPartialResults(bundle);
                } else {
                    if (DEBUG) {
                        MyLog.i(CLS_NAME, "onMessage: have final");
                    }
                    haveFinal.set(true);
                    if (doError.get()) {
                        stopListening();
                    }
                    for (int i = 0; i < resultsSize; i++) {
                        final List<Alternative> alternatives = results.get(i).getAlternatives();
                        final int size = alternatives.size();
                        if (DEBUG) {
                            MyLog.i(CLS_NAME, "final alternatives size: " + size);
                        }
                        for (int j = 0; j < size; j++) {
                            if (DEBUG) {
                                MyLog.i(CLS_NAME, "final result: " + alternatives.get(j).getTranscript() + " ~ " + alternatives.get(j).getConfidence());
                            }
                            confidenceArray.add(alternatives.get(j).getConfidence());
                            resultsArray.add(alternatives.get(j).getTranscript().trim());
                        }
                    }
                    Recognition.setState(Recognition.State.IDLE);
                    if (languageModel == SaiyDefaults.LanguageModel.IBM) {
                        if (DEBUG) {
                            MyLog.i(CLS_NAME, "final: nlu required");
                        }
                        if (servingRemote) {
                            bundle.putString(Request.RESULTS_NLU, message);
                            bundle.putFloatArray(SpeechRecognizer.CONFIDENCE_SCORES, ArrayUtils.toPrimitive(confidenceArray.toArray(new Float[0]), 0.0F));
                            bundle.putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, resultsArray);
                            listener.onResults(bundle);
                        } else {
                            new ResolveBluemix(mic.getContext(), sl, UtilsLocale.stringToLocale(vrLocale.toString()), ttsLocale, ArrayUtils.toPrimitive(confidenceArray.toArray(new Float[0]), 0.0F), resultsArray).unpack(nluBluemix);
                        }
                    } else {
                        if (DEBUG) {
                            MyLog.i(CLS_NAME, "final: nlu not required");
                        }
                        bundle.putFloatArray(SpeechRecognizer.CONFIDENCE_SCORES, ArrayUtils.toPrimitive(confidenceArray.toArray(new Float[0]), 0.0F));
                        bundle.putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, resultsArray);
                        listener.onResults(bundle);
                    }
                }
            } else {
                if (DEBUG) {
                    MyLog.w(CLS_NAME, "onMessage: nluBluemix results naked");
                }
            }
        }
    } else {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "onMessage: nluBluemix null");
        }
    }
}
Also used : ResolveBluemix(ai.saiy.android.nlu.bluemix.ResolveBluemix) Alternative(ai.saiy.android.nlu.bluemix.Alternative) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) JSONException(org.json.JSONException) JsonSyntaxException(com.google.gson.JsonSyntaxException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Result(ai.saiy.android.nlu.bluemix.Result) JsonSyntaxException(com.google.gson.JsonSyntaxException) NLUBluemix(ai.saiy.android.nlu.bluemix.NLUBluemix)

Aggregations

JsonSyntaxException (com.google.gson.JsonSyntaxException)379 Gson (com.google.gson.Gson)169 IOException (java.io.IOException)83 HashMap (java.util.HashMap)68 JsonElement (com.google.gson.JsonElement)62 JsonObject (com.google.gson.JsonObject)58 ArrayList (java.util.ArrayList)46 JsonParser (com.google.gson.JsonParser)42 GsonBuilder (com.google.gson.GsonBuilder)38 Cursor (android.database.Cursor)33 InputStreamReader (java.io.InputStreamReader)30 Map (java.util.Map)30 BadRequestException (co.cask.cdap.common.BadRequestException)28 JsonArray (com.google.gson.JsonArray)28 Path (javax.ws.rs.Path)28 Reader (java.io.Reader)26 Type (java.lang.reflect.Type)23 JsonIOException (com.google.gson.JsonIOException)21 FileReader (java.io.FileReader)21 File (java.io.File)19