package com.rthoni.intellij.codefromds.business; import com.intellij.database.psi.DbDataSource; import com.intellij.database.psi.DbPsiFacade; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.rthoni.intellij.codefromds.dbo.TableSelection; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * Created by robin on 11/15/16. */ public abstract class Helper { public static List getDataSources() { ProjectManager pm = ProjectManager.getInstance(); Project[] projects = pm.getOpenProjects(); return Arrays.stream(projects).map(project -> DbPsiFacade.getInstance(project).getDataSources()) .flatMap(Collection::stream).collect(Collectors.toList()); } public static DbDataSource findDataSource(String name) { Optional opt = getDataSources().stream().filter(d -> d.getName().equals(name)).findFirst(); if (opt.isPresent()) { return opt.get(); } return null; } public static JSONObject findTableInJson(JSONArray tables, String name) { for (int i = 0; i < tables.length(); ++i) { if (tables.getJSONObject(i).getString("table").equals(name)) { return tables.getJSONObject(i); } } return null; } public static JSONObject findColumnInJson(JSONArray tables, String name) { for (int i = 0; i < tables.length(); ++i) { if (tables.getJSONObject(i).getString("column").equals(name)) { return tables.getJSONObject(i); } } return null; } public static String readFile(String path) throws IOException { return Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8) .stream().reduce("", (s1, s2) -> s1 + s2 + "\n"); } }