Search in sources :

Example 26 with LinkedTreeMap

use of com.google.gson.internal.LinkedTreeMap in project components by Talend.

the class MarketoBaseRESTClient method executeFakeGetRequest.

public MarketoRecordResult executeFakeGetRequest(Schema schema, String input) throws MarketoException {
    InputStreamReader reader = httpFakeGet(input, false);
    // TODO refactor this part with method executeGetRequest(Schema s);
    Gson gson = new Gson();
    MarketoRecordResult mkr = new MarketoRecordResult();
    LinkedTreeMap ltm = (LinkedTreeMap) gson.fromJson(reader, Object.class);
    LOG.debug("ltm = {}.", ltm);
    mkr.setRequestId(REST + "::" + ltm.get("requestId"));
    mkr.setSuccess(Boolean.parseBoolean(ltm.get("success").toString()));
    mkr.setStreamPosition((String) ltm.get(FIELD_NEXT_PAGE_TOKEN));
    if (!mkr.isSuccess() && ltm.get(FIELD_ERRORS) != null) {
        List<LinkedTreeMap> errors = (List<LinkedTreeMap>) ltm.get(FIELD_ERRORS);
        for (LinkedTreeMap err : errors) {
            MarketoError error = new MarketoError(REST, (String) err.get("code"), (String) err.get("message"));
            mkr.setErrors(Collections.singletonList(error));
        }
    }
    if (mkr.isSuccess()) {
        List<LinkedTreeMap> tmp = (List<LinkedTreeMap>) ltm.get("result");
        if (tmp != null) {
            mkr.setRecordCount(tmp.size());
            mkr.setRecords(parseRecords(tmp, schema));
        }
        if (mkr.getStreamPosition() != null) {
            mkr.setRemainCount(mkr.getRecordCount());
        }
    }
    return mkr;
}
Also used : InputStreamReader(java.io.InputStreamReader) LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) ArrayList(java.util.ArrayList) List(java.util.List) MarketoRecordResult(org.talend.components.marketo.runtime.client.type.MarketoRecordResult) MarketoError(org.talend.components.marketo.runtime.client.type.MarketoError)

Example 27 with LinkedTreeMap

use of com.google.gson.internal.LinkedTreeMap in project ballerina by ballerina-lang.

the class CommandExecutor method executeAddDocumentation.

/**
 * Execute the add documentation command.
 * @param context   Workspace service context
 */
private static void executeAddDocumentation(WorkspaceServiceContext context) {
    String topLevelNodeType = "";
    String documentUri = "";
    int line = 0;
    VersionedTextDocumentIdentifier textDocumentIdentifier = new VersionedTextDocumentIdentifier();
    for (Object arg : context.get(ExecuteCommandKeys.COMMAND_ARGUMENTS_KEY)) {
        if (((LinkedTreeMap) arg).get(ARG_KEY).equals(CommandConstants.ARG_KEY_DOC_URI)) {
            documentUri = (String) ((LinkedTreeMap) arg).get(ARG_VALUE);
            textDocumentIdentifier.setUri(documentUri);
            context.put(DocumentServiceKeys.FILE_URI_KEY, documentUri);
        } else if (((LinkedTreeMap) arg).get(ARG_KEY).equals(CommandConstants.ARG_KEY_NODE_TYPE)) {
            topLevelNodeType = (String) ((LinkedTreeMap) arg).get(ARG_VALUE);
        } else if (((LinkedTreeMap) arg).get(ARG_KEY).equals(CommandConstants.ARG_KEY_NODE_LINE)) {
            line = Integer.parseInt((String) ((LinkedTreeMap) arg).get(ARG_VALUE));
        }
    }
    BLangPackage bLangPackage = TextDocumentServiceUtil.getBLangPackage(context, context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY), false, LSCustomErrorStrategy.class, false).get(0);
    CommandUtil.DocAttachmentInfo docAttachmentInfo = getDocumentEditForNodeByPosition(topLevelNodeType, bLangPackage, line);
    if (docAttachmentInfo != null) {
        String fileContent = context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY).getFileContent(Paths.get(URI.create(documentUri)));
        String[] contentComponents = fileContent.split(System.lineSeparator());
        int replaceEndCol = contentComponents[line - 1].length();
        String replaceText = String.join(System.lineSeparator(), Arrays.asList(Arrays.copyOfRange(contentComponents, 0, line))) + System.lineSeparator() + docAttachmentInfo.getDocAttachment();
        Range range = new Range(new Position(0, 0), new Position(line - 1, replaceEndCol));
        applySingleTextEdit(replaceText, range, textDocumentIdentifier, context.get(ExecuteCommandKeys.LANGUAGE_SERVER_KEY).getClient());
    }
}
Also used : VersionedTextDocumentIdentifier(org.eclipse.lsp4j.VersionedTextDocumentIdentifier) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) Position(org.eclipse.lsp4j.Position) Range(org.eclipse.lsp4j.Range) LSCustomErrorStrategy(org.ballerinalang.langserver.common.LSCustomErrorStrategy)

Example 28 with LinkedTreeMap

use of com.google.gson.internal.LinkedTreeMap in project ballerina by ballerina-lang.

the class CommandExecutor method executeImportPackage.

/**
 * Execute the command, import package.
 * @param context   Workspace service context
 */
private static void executeImportPackage(WorkspaceServiceContext context) {
    String documentUri = null;
    VersionedTextDocumentIdentifier textDocumentIdentifier = new VersionedTextDocumentIdentifier();
    for (Object arg : context.get(ExecuteCommandKeys.COMMAND_ARGUMENTS_KEY)) {
        if (((LinkedTreeMap) arg).get(ARG_KEY).equals(CommandConstants.ARG_KEY_DOC_URI)) {
            documentUri = (String) ((LinkedTreeMap) arg).get(ARG_VALUE);
            textDocumentIdentifier.setUri(documentUri);
            context.put(DocumentServiceKeys.FILE_URI_KEY, documentUri);
        } else if (((LinkedTreeMap) arg).get(ARG_KEY).equals(CommandConstants.ARG_KEY_PKG_NAME)) {
            context.put(ExecuteCommandKeys.PKG_NAME_KEY, (String) ((LinkedTreeMap) arg).get(ARG_VALUE));
        }
    }
    if (documentUri != null && context.get(ExecuteCommandKeys.PKG_NAME_KEY) != null) {
        String fileContent = context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY).getFileContent(Paths.get(URI.create(documentUri)));
        String[] contentComponents = fileContent.split("\\n|\\r\\n|\\r");
        int totalLines = contentComponents.length;
        int lastNewLineCharIndex = Math.max(fileContent.lastIndexOf("\n"), fileContent.lastIndexOf("\r"));
        int lastCharCol = fileContent.substring(lastNewLineCharIndex + 1).length();
        BLangPackage bLangPackage = TextDocumentServiceUtil.getBLangPackage(context, context.get(ExecuteCommandKeys.DOCUMENT_MANAGER_KEY), false, LSCustomErrorStrategy.class, false).get(0);
        context.put(DocumentServiceKeys.CURRENT_PACKAGE_NAME_KEY, bLangPackage.symbol.getName().getValue());
        String pkgName = context.get(ExecuteCommandKeys.PKG_NAME_KEY);
        DiagnosticPos pos;
        // Filter the imports except the runtime import
        List<BLangImportPackage> imports = bLangPackage.getImports().stream().filter(bLangImportPackage -> !bLangImportPackage.getAlias().toString().equals(RUNTIME_PKG_ALIAS)).collect(Collectors.toList());
        if (!imports.isEmpty()) {
            BLangImportPackage lastImport = bLangPackage.getImports().get(bLangPackage.getImports().size() - 1);
            pos = lastImport.getPosition();
        } else if (imports.isEmpty() && bLangPackage.getPackageDeclaration() != null) {
            pos = (DiagnosticPos) bLangPackage.getPackageDeclaration().getPosition();
        } else {
            pos = null;
        }
        int endCol = pos == null ? -1 : pos.getEndColumn() - 1;
        int endLine = pos == null ? 0 : pos.getEndLine() - 1;
        String remainingTextToReplace;
        if (endCol != -1) {
            int contentLengthToReplaceStart = fileContent.substring(0, fileContent.indexOf(contentComponents[endLine])).length() + endCol + 1;
            remainingTextToReplace = fileContent.substring(contentLengthToReplaceStart);
        } else {
            remainingTextToReplace = fileContent;
        }
        String editText = (pos != null ? "\r\n" : "") + "import " + pkgName + ";" + (remainingTextToReplace.startsWith("\n") || remainingTextToReplace.startsWith("\r") ? "" : "\r\n") + remainingTextToReplace;
        Range range = new Range(new Position(endLine, endCol + 1), new Position(totalLines + 1, lastCharCol));
        applySingleTextEdit(editText, range, textDocumentIdentifier, context.get(ExecuteCommandKeys.LANGUAGE_SERVER_KEY).getClient());
    }
}
Also used : CommonUtil(org.ballerinalang.langserver.common.utils.CommonUtil) LanguageClient(org.eclipse.lsp4j.services.LanguageClient) Arrays(java.util.Arrays) ApplyWorkspaceEditParams(org.eclipse.lsp4j.ApplyWorkspaceEditParams) WorkspaceServiceContext(org.ballerinalang.langserver.WorkspaceServiceContext) CommandConstants(org.ballerinalang.langserver.common.constants.CommandConstants) Range(org.eclipse.lsp4j.Range) ArrayList(java.util.ArrayList) BLangImportPackage(org.wso2.ballerinalang.compiler.tree.BLangImportPackage) BLangResource(org.wso2.ballerinalang.compiler.tree.BLangResource) TextEdit(org.eclipse.lsp4j.TextEdit) ExecuteCommandParams(org.eclipse.lsp4j.ExecuteCommandParams) TextDocumentEdit(org.eclipse.lsp4j.TextDocumentEdit) Position(org.eclipse.lsp4j.Position) VersionedTextDocumentIdentifier(org.eclipse.lsp4j.VersionedTextDocumentIdentifier) URI(java.net.URI) DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) DocumentServiceKeys(org.ballerinalang.langserver.DocumentServiceKeys) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) BLangFunction(org.wso2.ballerinalang.compiler.tree.BLangFunction) Collectors(java.util.stream.Collectors) BLangAnnotationAttachment(org.wso2.ballerinalang.compiler.tree.BLangAnnotationAttachment) BLangTransformer(org.wso2.ballerinalang.compiler.tree.BLangTransformer) TextDocumentServiceUtil(org.ballerinalang.langserver.TextDocumentServiceUtil) BLangNode(org.wso2.ballerinalang.compiler.tree.BLangNode) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) LSCustomErrorStrategy(org.ballerinalang.langserver.common.LSCustomErrorStrategy) List(java.util.List) BLangEnum(org.wso2.ballerinalang.compiler.tree.BLangEnum) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) Paths(java.nio.file.Paths) Node(org.ballerinalang.model.tree.Node) UtilSymbolKeys(org.ballerinalang.langserver.common.UtilSymbolKeys) BLangStruct(org.wso2.ballerinalang.compiler.tree.BLangStruct) LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) Collections(java.util.Collections) LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) Position(org.eclipse.lsp4j.Position) BLangImportPackage(org.wso2.ballerinalang.compiler.tree.BLangImportPackage) Range(org.eclipse.lsp4j.Range) DiagnosticPos(org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos) VersionedTextDocumentIdentifier(org.eclipse.lsp4j.VersionedTextDocumentIdentifier) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) LSCustomErrorStrategy(org.ballerinalang.langserver.common.LSCustomErrorStrategy)

Example 29 with LinkedTreeMap

use of com.google.gson.internal.LinkedTreeMap in project ButterRemote-Android by se-bastiaan.

the class PopcornTimeRpcClient method request.

/**
 * Send JSON RPC request to the instance
 * @param rpc Request data
 * @param callback Callback for the request
 * @return ResponseFuture
 */
private Call request(final RpcRequest rpc, final Callback callback) {
    RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, mGson.toJson(rpc));
    Request request = new Request.Builder().url(mUrl).header("Authorization", Credentials.basic(mUsername, mPassword)).post(requestBody).build();
    Call call = mClient.newCall(request);
    call.enqueue(new com.squareup.okhttp.Callback() {

        @Override
        public void onFailure(Request request, IOException e) {
            callback.onCompleted(e, null);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            RpcResponse result = null;
            Exception e = null;
            try {
                if (response != null && response.isSuccessful()) {
                    String responseStr = response.body().string();
                    // LogUtils.d("PopcornTimeRpcClient", "Response: " + responseStr);
                    result = mGson.fromJson(responseStr, RpcResponse.class);
                    LinkedTreeMap<String, Object> map = result.getMapResult();
                    if (map.containsKey("popcornVersion")) {
                        mVersion = (String) map.get("popcornVersion");
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                e = ex;
                mVersion = ZERO_VERSION;
                if (rpc.id == RequestId.GET_SELECTION.ordinal()) {
                    mVersion = "0.3.4";
                }
            }
            callback.onCompleted(e, result);
        }
    });
    return call;
}
Also used : Call(com.squareup.okhttp.Call) LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) Request(com.squareup.okhttp.Request) Callback(com.squareup.okhttp.Callback) IOException(java.io.IOException) IOException(java.io.IOException) Response(com.squareup.okhttp.Response) RequestBody(com.squareup.okhttp.RequestBody)

Example 30 with LinkedTreeMap

use of com.google.gson.internal.LinkedTreeMap in project LogisticsPipes by RS485.

the class VersionChecker method call.

@Override
public VersionInfo call() throws Exception {
    if (LogisticsPipes.UNKNOWN.equals(LogisticsPipes.getVERSION())) {
        return null;
    }
    VersionInfo versionInfo = new VersionInfo();
    URL url = new URL(String.format("http://rs485.network/version?VERSION=%s:%b", LogisticsPipes.getVERSION(), LogisticsPipes.isDEBUG()));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    InputStream inputStream = (InputStream) conn.getContent();
    String jsonString;
    try (Scanner sc = new Scanner(inputStream)) {
        sc.useDelimiter("\\A");
        jsonString = sc.next();
    }
    Gson gson = new Gson();
    LinkedTreeMap part = gson.fromJson(jsonString, LinkedTreeMap.class);
    Boolean hasNew = (Boolean) part.get("new");
    versionInfo.setNewVersionAvailable(hasNew);
    if (hasNew) {
        versionInfo.setNewestBuild(String.valueOf(part.get("build")));
        LogisticsPipes.log.info("New Logistics Pipes build found: #" + versionInfo.getNewestBuild());
        @SuppressWarnings("unchecked") LinkedTreeMap<String, List<String>> changelog = (LinkedTreeMap<String, List<String>>) part.get("changelog");
        List<String> changeLogList = new ArrayList<>();
        if (changelog != null) {
            for (String build : changelog.keySet()) {
                changeLogList.add(build + ": ");
                for (String commit : changelog.get(build)) {
                    if (commit.length() > COMMIT_MAX_LINE_LENGTH) {
                        String prefix = "    ";
                        boolean first = true;
                        while (!commit.isEmpty()) {
                            int maxLength;
                            if (first) {
                                maxLength = COMMIT_MAX_LINE_LENGTH;
                            } else {
                                maxLength = COMMIT_MAX_LINE_LENGTH - prefix.length();
                            }
                            int splitAt = commit.substring(0, Math.min(maxLength, commit.length())).lastIndexOf(' ');
                            if (commit.length() < COMMIT_MAX_LINE_LENGTH) {
                                splitAt = commit.length();
                            }
                            if (splitAt <= 0) {
                                splitAt = Math.min(maxLength, commit.length());
                            } else if (commit.length() > COMMIT_MAX_LINE_LENGTH && splitAt < COMMIT_MAX_LINE_LENGTH - 20) {
                                splitAt = Math.min(maxLength, commit.length());
                            }
                            changeLogList.add((first ? "" : prefix) + commit.substring(0, splitAt));
                            commit = commit.substring(splitAt);
                            first = false;
                        }
                    } else {
                        changeLogList.add(commit);
                    }
                }
            }
        }
        versionInfo.setChangelog(changeLogList);
        sendIMCOutdatedMessage(versionInfo);
    }
    return versionInfo;
}
Also used : Scanner(java.util.Scanner) LinkedTreeMap(com.google.gson.internal.LinkedTreeMap) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

LinkedTreeMap (com.google.gson.internal.LinkedTreeMap)30 Gson (com.google.gson.Gson)15 ArrayList (java.util.ArrayList)10 JsonObject (com.google.gson.JsonObject)6 HashMap (java.util.HashMap)6 InputStreamReader (java.io.InputStreamReader)5 URL (java.net.URL)5 List (java.util.List)5 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)3 LSCustomErrorStrategy (org.ballerinalang.langserver.common.LSCustomErrorStrategy)3 VersionedTextDocumentIdentifier (org.eclipse.lsp4j.VersionedTextDocumentIdentifier)3 MarketoException (org.talend.components.marketo.runtime.client.type.MarketoException)3 MarketoRecordResult (org.talend.components.marketo.runtime.client.type.MarketoRecordResult)3 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)3 NonNull (android.support.annotation.NonNull)2 Tuple2 (bisq.common.util.Tuple2)2 JsonElement (com.google.gson.JsonElement)2 StatusCallback (com.instructure.canvasapi2.StatusCallback)2