use of org.json.simple.parser.ParseException in project product-iots by wso2.
the class QSGUtils method getClientCredentials.
private static ClientCredentials getClientCredentials() {
ClientCredentials clientCredentials = null;
HashMap<String, String> headers = new HashMap<String, String>();
EMMQSGConfig emmqsgConfig = EMMQSGConfig.getInstance();
String dcrEndPoint = emmqsgConfig.getDcrEndPoint();
// Set the DCR payload
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
arr.add("android");
arr.add("device_management");
obj.put("applicationName", "qsg");
obj.put("tags", arr);
obj.put("isAllowedToAllDomains", false);
obj.put("isMappingAnExistingOAuthApp", false);
String authorizationStr = emmqsgConfig.getUsername() + ":" + emmqsgConfig.getPassword();
String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes()));
headers.put(Constants.Header.AUTH, authHeader);
// Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse httpResponse = HTTPInvoker.sendHTTPPost(dcrEndPoint, obj.toJSONString(), headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
try {
JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
clientCredentials = new ClientCredentials();
clientCredentials.setClientKey((String) jsonObject.get("client_id"));
clientCredentials.setClientSecret((String) jsonObject.get("client_secret"));
} catch (ParseException e) {
e.printStackTrace();
}
}
return clientCredentials;
}
use of org.json.simple.parser.ParseException in project product-iots by wso2.
the class QSGUtils method getOAuthToken.
public static String getOAuthToken() {
QSGUtils.initConfig();
ClientCredentials clientCredentials = getClientCredentials();
String authorizationStr = clientCredentials.getClientKey() + ":" + clientCredentials.getClientSecret();
String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes()));
HashMap<String, String> headers = new HashMap<String, String>();
// Set the form params
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", EMMQSGConfig.getInstance().getUsername()));
urlParameters.add(new BasicNameValuePair("password", EMMQSGConfig.getInstance().getPassword()));
urlParameters.add(new BasicNameValuePair("grant_type", "password"));
urlParameters.add(new BasicNameValuePair("scope", "user:view user:manage user:admin:reset-password role:view role:manage policy:view policy:manage " + "application:manage appm:administration appm:create appm:publish appm:update appm:read"));
// Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_URL_ENCODED);
headers.put(Constants.Header.AUTH, authHeader);
HTTPResponse httpResponse = HTTPInvoker.sendHTTPPostWithURLParams(EMMQSGConfig.getInstance().getOauthEndPoint(), urlParameters, headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) {
try {
JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
return (String) jsonObject.get("access_token");
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
use of org.json.simple.parser.ParseException in project LanternServer by LanternPowered.
the class LanternClassLoader method load.
private static LanternClassLoader load() throws IOException {
ClassLoader.registerAsParallelCapable();
// Get the bootstrap class loader
final ClassLoader classLoader = LanternClassLoader.class.getClassLoader();
// Load the dependencies files
final List<Dependencies> dependenciesEntries = new ArrayList<>();
// Load the dependencies file within the jar, not available in the IDE
final URL dependenciesURL = classLoader.getResource("dependencies.json");
if (dependenciesURL != null) {
try {
dependenciesEntries.add(DependenciesParser.read(new BufferedReader(new InputStreamReader(dependenciesURL.openStream()))));
} catch (ParseException e) {
throw new IllegalStateException("Failed to parse the dependencies.json file within the jar.", e);
}
}
// Try to generate or load the dependencies file
final Path dependenciesFile = Paths.get("dependencies.json");
if (!Files.exists(dependenciesFile)) {
try (BufferedWriter writer = Files.newBufferedWriter(dependenciesFile)) {
writer.write("{\n \"repositories\": [\n ],\n \"dependencies\": [\n ]\n}");
}
} else {
try {
dependenciesEntries.add(DependenciesParser.read(Files.newBufferedReader(dependenciesFile)));
} catch (ParseException e) {
throw new IllegalStateException("Failed to parse the dependencies.json file within the root directory.", e);
}
}
// Merge the dependencies files
final List<URL> repositoryUrls = new ArrayList<>();
final Map<String, Dependency> dependencyMap = new HashMap<>();
for (Dependencies dependencies : dependenciesEntries) {
dependencies.getRepositories().stream().map(Repository::getUrl).filter(e -> !repositoryUrls.contains(e)).forEach(repositoryUrls::add);
for (Dependency dependency : dependencies.getDependencies()) {
dependencyMap.put(dependency.getGroup() + ':' + dependency.getName(), dependency);
}
}
String localRepoPath = System.getProperty("maven.repo.local");
if (localRepoPath == null) {
final String mavenHome = System.getenv("M2_HOME");
if (mavenHome != null) {
final Path settingsPath = Paths.get(mavenHome, "conf", "setting.xml");
if (Files.exists(settingsPath)) {
try {
final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final Document document = documentBuilder.parse(settingsPath.toFile());
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
final Node node = document.getElementsByTagName("localRepository").item(0);
if (node != null) {
localRepoPath = node.getTextContent();
}
} catch (ParserConfigurationException | SAXException e) {
throw new IllegalStateException(e);
}
}
}
}
if (localRepoPath == null) {
localRepoPath = "~/.m/repository";
}
localRepoPath = localRepoPath.trim();
if (localRepoPath.charAt(0) == '~') {
localRepoPath = System.getProperty("user.home") + '/' + localRepoPath.substring(2);
}
// Try to find the local maven repository
repositoryUrls.add(0, new File(localRepoPath).toURL());
final List<FileRepository> repositories = new ArrayList<>();
for (URL repositoryUrl : repositoryUrls) {
if (repositoryUrl.getProtocol().equals("file")) {
final File baseFile = new File(repositoryUrl.getFile());
repositories.add(path -> {
final File file = new File(baseFile, path);
try {
return file.exists() ? file.toURL().openStream() : null;
} catch (IOException e) {
throw new IllegalStateException(e);
}
});
} else {
String repositoryUrlBase = repositoryUrl.toString();
if (repositoryUrlBase.endsWith("/")) {
repositoryUrlBase = repositoryUrlBase.substring(0, repositoryUrlBase.length() - 1);
}
final String urlBase = repositoryUrlBase;
repositories.add(path -> {
try {
final URL url = new URL(urlBase + "/" + path);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
final String encoding = connection.getHeaderField("Content-Encoding");
InputStream is = connection.getInputStream();
if (encoding != null) {
if (encoding.equals("gzip")) {
is = new GZIPInputStream(is);
} else {
throw new IllegalStateException("Unsupported encoding: " + encoding);
}
}
return is;
} catch (IOException e) {
return null;
}
});
}
}
// If we are outside development mode, the server will be packed
// into a jar. We will also need to make sure that this one gets
// added in this case
final CodeSource source = LanternClassLoader.class.getProtectionDomain().getCodeSource();
final URL location = source == null ? null : source.getLocation();
// Setup the environment variable
final String env = System.getProperty(ENVIRONMENT);
final Environment environment;
if (env != null) {
try {
environment = Environment.valueOf(env.toUpperCase());
} catch (IllegalArgumentException e) {
throw new RuntimeException("Invalid environment type: " + env);
}
} else {
environment = location == null || new File(location.getFile()).isDirectory() ? Environment.DEVELOPMENT : Environment.PRODUCTION;
System.setProperty(ENVIRONMENT, environment.toString().toLowerCase());
}
Environment.set(environment);
// Scan the jar for library jars
if (location != null) {
repositories.add(path -> classLoader.getResourceAsStream("dependencies/" + path));
}
final List<URL> libraryUrls = new ArrayList<>();
// Download or load all the dependencies
final Path internalLibrariesPath = Paths.get(".cached-dependencies");
for (Dependency dependency : dependencyMap.values()) {
final String group = dependency.getGroup();
final String name = dependency.getName();
final String version = dependency.getVersion();
final Path target = internalLibrariesPath.resolve(String.format("%s/%s/%s/%s-%s.jar", group.replace('.', '/'), name, version, name, version));
libraryUrls.add(target.toUri().toURL());
final String id = String.format("%s:%s:%s", dependency.getGroup(), dependency.getName(), dependency.getVersion());
if (Files.exists(target)) {
System.out.printf("Loaded: \"%s\"\n", id);
continue;
}
InputStream is = null;
for (FileRepository repository : repositories) {
is = repository.get(dependency);
if (is != null) {
break;
}
}
if (is == null) {
throw new IllegalStateException("The following dependency could not be found: " + id);
}
final Path parent = target.getParent();
if (!Files.exists(parent)) {
Files.createDirectories(parent);
}
System.out.printf("Downloading \"%s\"\n", id);
try (ReadableByteChannel i = Channels.newChannel(is);
FileOutputStream o = new FileOutputStream(target.toFile())) {
o.getChannel().transferFrom(i, 0, Long.MAX_VALUE);
}
}
// All the folders are from lantern or sponge,
// in development mode are all the libraries on
// the classpath, so there is no need to add them
// to the library classloader
final List<URL> urls = new ArrayList<>();
final String classPath = System.getProperty("java.class.path");
final String[] libraries = classPath.split(File.pathSeparator);
for (String library : libraries) {
try {
final URL url = Paths.get(library).toUri().toURL();
if (!library.endsWith(".jar") || url.equals(location)) {
urls.add(url);
}
} catch (MalformedURLException ignored) {
System.out.println("Invalid library found in the class path: " + library);
}
}
// The server class loader will load lantern, the api and all the plugins
final LanternClassLoader serverClassLoader = new LanternClassLoader(urls.toArray(new URL[urls.size()]), libraryUrls.toArray(new URL[libraryUrls.size()]), classLoader);
Thread.currentThread().setContextClassLoader(serverClassLoader);
return serverClassLoader;
}
use of org.json.simple.parser.ParseException in project VoxelGamesLibv2 by VoxelGamesLib.
the class MojangUtil method getDisplayName.
// TODO we need to do some caching to not break mojang api rate limits
/**
* Tries to fetch the current display name for the user
*
* @param id the id of the user to check
* @return the current display name of that user
* @throws IOException if something goes wrong
* @throws VoxelGameLibException if the user has no display name
*/
@Nonnull
public static String getDisplayName(@Nonnull UUID id) throws IOException, VoxelGameLibException {
URL url = new URL(NAME_HISTORY_URL.replace("%1", id.toString().replace("-", "")));
System.out.println(url.toString());
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(url.openStream())));
if (scanner.hasNext()) {
String json = scanner.nextLine();
try {
JSONArray jsonArray = (JSONArray) new JSONParser().parse(json);
if (json.length() > 0) {
return (String) ((JSONObject) jsonArray.get(0)).get("name");
}
} catch (ParseException ignore) {
}
}
throw new VoxelGameLibException("User has no name! " + id);
}
use of org.json.simple.parser.ParseException in project chatty by chatty.
the class FrankerFaceZParsing method parseSetEmotes.
/**
* Parses the emotes of the set request.
*
* Request: /set/:id
*
* @param json The JSON to parse
* @param subType
* @return
*/
public static Set<Emoticon> parseSetEmotes(String json, Emoticon.SubType subType, String room) {
try {
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(json);
JSONObject setData = (JSONObject) root.get("set");
return parseEmoteSet(setData, room, subType);
} catch (ParseException | ClassCastException | NullPointerException ex) {
LOGGER.warning("Error parsing FFZ emotes: " + ex);
}
return new HashSet<>();
}
Aggregations