@Override protected String extractErrorMessage(String response) { if (response != null && !response.isEmpty()) { try { JSON jsonResponse = JSONSerializer.toJSON(response, new JsonConfig()); if (jsonResponse instanceof JSONObject) { JSONObject object = (JSONObject) jsonResponse; JSONObject errorObj = object.getJSONObject("error"); if (errorObj.containsKey("message")) { return errorObj.getString("message"); } } } catch (JSONException ex) { log.debug("Cannot parse JSON error response: " + response); } } return response; }
public static LimitViolation jsonToLimitViolation(String json, Network network) { JSONObject jsonObj = (JSONObject) JSONSerializer.toJSON(json); Map<String, String> limitViolation = (Map<String, String>) JSONObject.toBean(jsonObj, Map.class); Country country = null; if (limitViolation.containsKey("Country")) { country = Country.valueOf(limitViolation.get("Country")); } float baseVoltage = Float.NaN; if (limitViolation.containsKey("BaseVoltage")) { baseVoltage = Float.parseFloat(limitViolation.get("BaseVoltage")); } float limitReduction = 1f; if (limitViolation.containsKey("LimitReduction")) { limitReduction = Float.parseFloat(limitViolation.get("LimitReduction")); } return new LimitViolation(limitViolation.get("Subject"), LimitViolationType.valueOf(limitViolation.get("LimitType")), Float.parseFloat(limitViolation.get("Limit")), limitViolation.get("LimitName"), limitReduction, Float.parseFloat(limitViolation.get("Value")), country, baseVoltage); }
public ActionForward checkForDx(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String demographicNo = request.getParameter("demographicNo"); String codingSystem = request.getParameter("codingSystem"); String code = request.getParameter("code"); boolean exists = dxResearchDao.activeEntryExists(Integer.parseInt(demographicNo), codingSystem, code); String str = "{'result':"+exists+"}"; JSONObject jsonArray = (JSONObject) JSONSerializer.toJSON(str); response.setContentType("text/x-json"); try { jsonArray.write(response.getWriter()); }catch(IOException e) { MiscUtils.getLogger().error("Error",e); } return null; }
public ActionForward unspecified(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{ String searchStr=request.getParameter("providerKeyword"); if(searchStr==null){ searchStr=request.getParameter("query"); } if(searchStr==null){ searchStr=request.getParameter("name"); } MiscUtils.getLogger().info("Search Provider " + searchStr); List provList=ProviderData.searchProvider(searchStr,true); Hashtable d=new Hashtable(); d.put("results", provList); response.setContentType("text/x-json"); JSONObject jsonArray=(JSONObject) JSONSerializer.toJSON(d); jsonArray.write(response.getWriter()); return null; }
/** * Creates a web hook in Gogs with the passed json configuration string * * @param jsonCommand A json buffer with the creation command of the web hook * @param projectName the project (owned by the user) where the webHook should be created * @throws IOException something went wrong */ int createWebHook(String jsonCommand, String projectName) throws IOException { String gogsHooksConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName + "/hooks"; Executor executor = getExecutor(); String result = executor .execute(Request.Post(gogsHooksConfigUrl).bodyString(jsonCommand, ContentType.APPLICATION_JSON)) .returnContent().asString(); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( result ); int id = jsonObject.getInt("id"); return id; }
/** * Validates the request parameter sourceArray * * @param sourceArray The request parameter sourceArray * @return true if validated */ private boolean isSourceArrayValid(String sourceArray) { JSONArray sourceJSON; try { sourceJSON = (JSONArray) JSONSerializer.toJSON(sourceArray); } catch (JSONException ex) { logger.error("JSONException : " + ex); return false; } if (!prepareLists(sourceJSON)) { throw new OperationFailedException("The requested resource(s) do not exist in the " + "repository. " + "Aborting operation."); } extensionsList = getListOfExtensionsFromSettings(); return (extensionsList != null); }
@Override public void setRequestData(String data) { requestParameterJson = (JSONObject) JSONSerializer.toJSON(data); String downloadType = requestParameterJson.optString("type"); // Set the content type for the response from the properties file this.contentType = (propertyMap.get(downloadType)); if (downloadType == null || downloadType.isEmpty()) { //Default type being csv format this.fileExtension = ".csv"; downloadType = "csv"; } else { this.fileExtension = "." + downloadType; } String beanName = settingsDownloadMap.get(downloadType); iDownload = (IDownload) ApplicationContextAccessor.getBean(beanName); CacheManager = this.getCacheManager(); CacheManager.setRequestData(data); }
@Test public void testMarshalAndUnmarshal() throws Exception { InputStream inStream = getClass().getResourceAsStream("testMessage1.xml"); String in = context.getTypeConverter().convertTo(String.class, inStream); MockEndpoint mockJSON = getMockEndpoint("mock:json"); mockJSON.expectedMessageCount(1); mockJSON.message(0).body().isInstanceOf(byte[].class); MockEndpoint mockXML = getMockEndpoint("mock:xml"); mockXML.expectedMessageCount(1); mockXML.message(0).body().isInstanceOf(String.class); Object json = template.requestBody("direct:marshal", in); String jsonString = context.getTypeConverter().convertTo(String.class, json); JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); assertEquals("JSONObject doesn't contain 7 keys", 7, obj.entrySet().size()); template.sendBody("direct:unmarshal", jsonString); mockJSON.assertIsSatisfied(); mockXML.assertIsSatisfied(); }
@Test public void testSomeOptionsToJSON() throws Exception { InputStream inStream = getClass().getClassLoader().getResourceAsStream("org/apache/camel/dataformat/xmljson/testMessage1.xml"); String in = context.getTypeConverter().convertTo(String.class, inStream); MockEndpoint mockJSON = getMockEndpoint("mock:json"); mockJSON.expectedMessageCount(1); mockJSON.message(0).body().isInstanceOf(byte[].class); Object json = template.requestBody("direct:marshal", in); String jsonString = context.getTypeConverter().convertTo(String.class, json); JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); assertEquals("JSON must contain 1 top-level element", 1, obj.entrySet().size()); assertTrue("Top-level element must be named root", obj.has("root")); mockJSON.assertIsSatisfied(); }
@Test public void testXmlWithTypeAttributesToJSON() throws Exception { InputStream inStream = getClass().getClassLoader().getResourceAsStream("org/apache/camel/dataformat/xmljson/testMessage4.xml"); String in = context.getTypeConverter().convertTo(String.class, inStream); MockEndpoint mockJSON = getMockEndpoint("mock:json"); mockJSON.expectedMessageCount(1); mockJSON.message(0).body().isInstanceOf(byte[].class); Object json = template.requestBody("direct:marshal", in); String jsonString = context.getTypeConverter().convertTo(String.class, json); JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); assertEquals("JSON must contain 1 top-level element", 1, obj.entrySet().size()); assertTrue("Top-level element must be named root", obj.has("root")); mockJSON.assertIsSatisfied(); }
@Test public void testNamespacesDropped() throws Exception { InputStream inStream = getClass().getClassLoader().getResourceAsStream("org/apache/camel/dataformat/xmljson/testMessage2-namespaces.xml"); String in = context.getTypeConverter().convertTo(String.class, inStream); MockEndpoint mockJSON = getMockEndpoint("mock:json"); mockJSON.expectedMessageCount(1); mockJSON.message(0).body().isInstanceOf(byte[].class); Object json = template.requestBody("direct:marshal", in); String jsonString = context.getTypeConverter().convertTo(String.class, json); JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); assertEquals("JSON must contain 1 top-level element", 1, obj.entrySet().size()); assertTrue("Top-level element must be named root", obj.has("root")); // check that no child of the top-level element has a colon in its key, // which would denote that // a namespace prefix exists for (Object key : obj.getJSONObject("root").keySet()) { assertFalse("A key contains a colon", ((String) key).contains(":")); } mockJSON.assertIsSatisfied(); }
@Test public void testTypeHintsToJSON() throws Exception { InputStream inStream = getClass().getClassLoader().getResourceAsStream("org/apache/camel/dataformat/xmljson/testMessage5-typeHints.xml"); String in = context.getTypeConverter().convertTo(String.class, inStream); MockEndpoint mockJSON = getMockEndpoint("mock:jsonTypeHints"); mockJSON.expectedMessageCount(1); mockJSON.message(0).body().isInstanceOf(byte[].class); Object json = template.requestBody("direct:marshalTypeHints", in); String jsonString = context.getTypeConverter().convertTo(String.class, json); JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); assertEquals("root.a must be number", Integer.valueOf(1), obj.getJSONObject("root").get("a")); assertEquals("root.b must be boolean", Boolean.TRUE, obj.getJSONObject("root").get("b")); mockJSON.assertIsSatisfied(); }
@Test public void testPrefixedTypeHintsToJSON() throws Exception { InputStream inStream = getClass().getClassLoader().getResourceAsStream("org/apache/camel/dataformat/xmljson/testMessage6-prefixedTypeHints.xml"); String in = context.getTypeConverter().convertTo(String.class, inStream); MockEndpoint mockJSON = getMockEndpoint("mock:jsonPrefixedTypeHints"); mockJSON.expectedMessageCount(1); mockJSON.message(0).body().isInstanceOf(byte[].class); Object json = template.requestBody("direct:marshalPrefixedTypeHints", in); String jsonString = context.getTypeConverter().convertTo(String.class, json); JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); assertEquals("root.a must be number", Integer.valueOf(1), obj.getJSONObject("root").get("a")); assertEquals("root.b must be boolean", Boolean.TRUE, obj.getJSONObject("root").get("b")); mockJSON.assertIsSatisfied(); }
@Test public void testUnmarshalJSONObject() throws Exception { InputStream inStream = getClass().getResourceAsStream("testMessage1.json"); String in = context.getTypeConverter().convertTo(String.class, inStream); JSON json = JSONSerializer.toJSON(in); MockEndpoint mockXML = getMockEndpoint("mock:xml"); mockXML.expectedMessageCount(1); mockXML.message(0).body().isInstanceOf(String.class); Object marshalled = template.requestBody("direct:unmarshal", json); Document document = context.getTypeConverter().convertTo(Document.class, marshalled); assertEquals("The XML document has an unexpected root node", "o", document.getDocumentElement().getLocalName()); mockXML.assertIsSatisfied(); }
@Test public void testMarshalAndUnmarshalInline() throws Exception { InputStream inStream = getClass().getResourceAsStream("testMessage1.xml"); String in = context.getTypeConverter().convertTo(String.class, inStream); MockEndpoint mockJSON = getMockEndpoint("mock:jsonInline"); mockJSON.expectedMessageCount(1); mockJSON.message(0).body().isInstanceOf(byte[].class); MockEndpoint mockXML = getMockEndpoint("mock:xmlInline"); mockXML.expectedMessageCount(1); mockXML.message(0).body().isInstanceOf(String.class); Object json = template.requestBody("direct:marshalInline", in); String jsonString = context.getTypeConverter().convertTo(String.class, json); JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); assertEquals("JSONObject doesn't contain 7 keys", 7, obj.entrySet().size()); template.sendBody("direct:unmarshalInline", jsonString); mockJSON.assertIsSatisfied(); mockXML.assertIsSatisfied(); }
@Test public void testNamespacesDroppedInlineWithOptions() throws Exception { InputStream inStream = getClass().getResourceAsStream("testMessage2-namespaces.xml"); String in = context.getTypeConverter().convertTo(String.class, inStream); MockEndpoint mockJSON = getMockEndpoint("mock:jsonInlineOptions"); mockJSON.expectedMessageCount(1); mockJSON.message(0).body().isInstanceOf(byte[].class); Object json = template.requestBody("direct:marshalInlineOptions", in); String jsonString = context.getTypeConverter().convertTo(String.class, json); JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); assertEquals("JSON must contain 1 top-level element", 1, obj.entrySet().size()); assertTrue("Top-level element must be named root", obj.has("root")); // check that no child of the top-level element has a colon in its key, // which would denote that // a namespace prefix exists for (Object key : obj.getJSONObject("root").keySet()) { assertFalse("A key contains a colon", ((String) key).contains(":")); } mockJSON.assertIsSatisfied(); }
public String getIpAddress(String containerName) throws IOException, InterruptedException, DockerClientException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ByteArrayOutputStream errStream = new ByteArrayOutputStream(); Launcher.ProcStarter ps = launcher.new ProcStarter(); ps.cmdAsSingleString(String.format(DOCKER_INSPECT, containerName)); ps.stdout(stream).stderr(errStream); ps = ps.pwd(build.getWorkspace()).envs(build.getEnvironment(listener)); Proc p = launcher.launch(ps); if (p.join() != 0) { throw new DockerClientException(getErrorMessage(errStream)); } JSONArray info = (JSONArray) JSONSerializer.toJSON(stream.toString()); return (String) ((JSONObject) info.getJSONObject(0).get(NETWORK_SETTINGS_FIELD)).get(IP_ADDRESS_FIELD); }
public boolean checkVmExists(String vmId) { try { RunVmCallable command = new RunVmCallable("list", "-i", "--json"); String callResult = forceGetChannel().call(command); JSONArray vms = (JSONArray)JSONSerializer.toJSON(callResult); for (int i = 0; i < vms.size(); i++) { JSONObject vmInfo = vms.getJSONObject(i); if (vmId.equals(vmInfo.getString("ID")) || vmId.equals(vmInfo.getString("Name"))) return true; } return true; } catch (Exception ex) { LOGGER.log(Level.SEVERE, ex.toString()); } return false; }
private String getVmIPAddress(String vmId) throws Exception { int TIMEOUT = 60; for (int i = 0; i < TIMEOUT; ++i) { RunVmCallable command = new RunVmCallable("list", "-f", "--json", vmId); String callResult = forceGetChannel().call(command); LOGGER.log(Level.SEVERE, " - (" + i + "/" + TIMEOUT + ") calling for IP"); LOGGER.log(Level.SEVERE, callResult); JSONArray vms = (JSONArray)JSONSerializer.toJSON(callResult); JSONObject vmInfo = vms.getJSONObject(0); String ip = vmInfo.getString("ip_configured"); if (!ip.equals("-")) return ip; Thread.sleep(1000); } throw new Exception("Failed to get IP for VM '" + vmId + "'"); }
private void writeFileFromGitUrl(String strGitUrl, String strFileName){ try { File file = new File(strFileName); File dir = file.getParentFile(); if(!dir.exists()) dir.mkdirs(); String strJSON = getDataFromUrl(strGitUrl); JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(strJSON); if(jsonObj.has("content")){ BASE64Decoder decoder = new BASE64Decoder(); byte[] decodeData = decoder.decodeBuffer(jsonObj.getString("content")); FileOutputStream os = new FileOutputStream(file); os.write(decodeData); os.close(); } System.out.println("Downloaded!\t" + strFileName); }catch(JSONException ex){ System.out.println("JSON Parse Error: " + ex.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Write File Error: " + e.getMessage()); } }
/** * ������Ϣ���� * @param strMsg ������Ϣ * @return void */ private void errHandle(String strMsg){ try{ JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(strMsg); String msg = jsonObj.getString("message"); String strErrorMsg = "Error: " + msg +". "; if(jsonObj.has("errors")){ JSONArray errArray = jsonObj.getJSONArray("errors"); Iterator<JSONObject> it = errArray.iterator(); while(it.hasNext()){ JSONObject errObj = it.next(); if(errObj.has("message")) strErrorMsg += errObj.getString("message")+". "; } } System.out.println(strErrorMsg); }catch(JSONException ex){ //ex.printStackTrace(); System.out.println("Error: " + strMsg); } }
/** * Return a representation of a deployment process for a given project. * @param projectId project id * @return DeploymentProcessTemplate deployment process template * @throws IllegalArgumentException when the web client receives a bad parameter * @throws IOException When the AuthenticatedWebClient receives and error response code */ public DeploymentProcessTemplate getDeploymentProcessTemplateForProject(String projectId) throws IllegalArgumentException, IOException { AuthenticatedWebClient.WebResponse response = webClient.get("api/deploymentprocesses/deploymentprocess-" + projectId + "/template"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); Set<SelectedPackage> packages = new HashSet<SelectedPackage>(); String deploymentId = json.getString("DeploymentProcessId"); JSONArray pkgsJson = json.getJSONArray("Packages"); for (Object pkgObj : pkgsJson) { JSONObject pkgJsonObj = (JSONObject) pkgObj; String name = pkgJsonObj.getString("StepName"); String packageId = pkgJsonObj.getString("PackageId"); String version = pkgJsonObj.getString("VersionSelectedLastRelease"); packages.add(new SelectedPackage(name, packageId, version)); } DeploymentProcessTemplate template = new DeploymentProcessTemplate(deploymentId, projectId, packages); return template; }
/** * Get all releases for a given project from the Octopus server; * @param projectId the id of the project to get the releases for * @return A set of all releases for a given project * @throws IllegalArgumentException when the web client receives a bad parameter * @throws IOException When the AuthenticatedWebClient receives and error response code */ public Set<Release> getReleasesForProject(String projectId) throws IllegalArgumentException, IOException { HashSet<Release> releases = new HashSet<Release>(); AuthenticatedWebClient.WebResponse response = webClient.get("api/projects/" + projectId + "/releases"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); for (Object obj : json.getJSONArray("Items")) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String version = jsonObj.getString("Version"); String channelId = jsonObj.getString("ChannelId"); String ReleaseNotes = jsonObj.getString("ReleaseNotes"); releases.add(new Release(id, projectId, channelId, ReleaseNotes, version)); } return releases; }
/** * Get all environments from the Octopus server as Environment objects. * @return A set of all environments on the Octopus server. * @throws IllegalArgumentException when the web client receives a bad parameter * @throws IOException When the AuthenticatedWebClient receives and error response code */ public Set<Environment> getAllEnvironments() throws IllegalArgumentException, IOException { HashSet<Environment> environments = new HashSet<Environment>(); AuthenticatedWebClient.WebResponse response =webClient.get("api/environments/all"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONArray json = (JSONArray)JSONSerializer.toJSON(response.getContent()); for (Object obj : json) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String name = jsonObj.getString("Name"); String description = jsonObj.getString("Description"); environments.add(new Environment(id, name, description)); } return environments; }
/** * Uses the authenticated web client to pull all channels for a given project * from the api and convert them to POJOs * @param projectId the project to get channels for * @return a Set of Channels (should have at minimum one entry) * @throws IllegalArgumentException when the web client receives a bad parameter * @throws IOException When the AuthenticatedWebClient receives and error response code */ public Set<Channel> getChannelsByProjectId(String projectId) throws IllegalArgumentException, IOException { HashSet<Channel> channels = new HashSet<Channel>(); AuthenticatedWebClient.WebResponse response = webClient.get("api/projects/" + projectId + "/channels"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); for (Object obj : json.getJSONArray("Items")) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String name = jsonObj.getString("Name"); String description = jsonObj.getString("Description"); boolean isDefault = jsonObj.getBoolean("IsDefault"); channels.add(new Channel(id, name, description, projectId, isDefault)); } return channels; }
/** * Uses the authenticated web client to pull a channel by name from a given project * from the api and convert them to POJOs * @param projectId the project to get channels for * @param channelName the channel to return * @return the named channel for the given project * @throws IllegalArgumentException when the web client receives a bad parameter * @throws IOException When the AuthenticatedWebClient receives and error response code */ public Channel getChannelByName(String projectId, String channelName) throws IllegalArgumentException, IOException { AuthenticatedWebClient.WebResponse response = webClient.get("api/projects/" + projectId + "/channels"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONObject json = (JSONObject)JSONSerializer.toJSON(response.getContent()); for (Object obj : json.getJSONArray("Items")) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String name = jsonObj.getString("Name"); String description = jsonObj.getString("Description"); boolean isDefault = jsonObj.getBoolean("IsDefault"); if (channelName.equals(name)) { return new Channel(id, name, description, projectId, isDefault); } } return null; }
/** * Uses the authenticated web client to pull all projects from the api and * convert them to POJOs * @return a Set of Projects (may be empty) * @throws IllegalArgumentException when the web client receives a bad parameter * @throws IOException When the AuthenticatedWebClient receives and error response code */ public Set<Project> getAllProjects() throws IllegalArgumentException, IOException { HashSet<Project> projects = new HashSet<Project>(); AuthenticatedWebClient.WebResponse response = webClient.get("api/projects/all"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONArray json = (JSONArray)JSONSerializer.toJSON(response.getContent()); for (Object obj : json) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String name = jsonObj.getString("Name"); projects.add(new Project(id, name)); } return projects; }
/** * Uses the authenticated web client to pull all tenants from the api and * convert them to POJOs * @return a Set of Tenants (may be empty) * @throws IllegalArgumentException when the web client receives a bad parameter * @throws IOException When the AuthenticatedWebClient receives and error response code */ public Set<Tenant> getAllTenants() throws IllegalArgumentException, IOException { HashSet<Tenant> tenants = new HashSet<Tenant>(); AuthenticatedWebClient.WebResponse response = webClient.get("api/tenants/all"); if (response.isErrorCode()) { throw new IOException(String.format("Code %s - %n%s", response.getCode(), response.getContent())); } JSONArray json = (JSONArray)JSONSerializer.toJSON(response.getContent()); for (Object obj : json) { JSONObject jsonObj = (JSONObject)obj; String id = jsonObj.getString("Id"); String name = jsonObj.getString("Name"); tenants.add(new Tenant(id, name)); } return tenants; }
/** * Call a generic Telegram web API. */ public Vertex postJSON(String url, Vertex paramsObject, Network network) { log("POST JSON:", Level.INFO, url); try { Map<String, String> params = getBot().awareness().getSense(Http.class).convertToMap(paramsObject); String json = Utils.httpPOST("https://api.telegram.org/bot" + this.token + "/" + url, params); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = getBot().awareness().getSense(Http.class).convertElement(root, network); return object; } catch (Exception exception) { this.errors++; log(exception); } return null; }
public void processSlackEvent(String json) { JSONObject root = (JSONObject)JSONSerializer.toJSON(json); JSONObject event = root.getJSONObject("event"); String token = root.getString("token"); if(event.getString("type").equals("message")) { String user = event.getString("user"); String channel = event.getString("channel"); String text = event.getString("text"); String reply = this.processMessage(user, channel, text, token); if (reply == null || reply.isEmpty()) { return; } String data = "token=" + this.appToken; data += "&channel=" + channel; data += "&text=" + "@" + user + " " + reply; this.callSlackWebAPI("chat.postMessage", data); } }
/** * Retrieves access token for bot */ protected void getAccessToken() throws Exception { String url = "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token"; String type = "application/x-www-form-urlencoded"; String data = "grant_type=client_credentials&client_id=" + appId + "&client_secret=" + appPassword + "&scope=https%3A%2F%2Fapi.botframework.com%2F.default"; String json = Utils.httpPOST(url, type, data); JSONObject root = (JSONObject)JSONSerializer.toJSON(json); if(root.optString("token_type").equals("Bearer")) { int tokenExpiresIn = root.optInt("expires_in"); String accessToken = root.optString("access_token"); setToken(accessToken); this.tokenExpiry = new Date(System.currentTimeMillis() + (tokenExpiresIn * 1000)); log("Skype access token retrieved.", Level.INFO); } else { log("Skype get access token failed:", Level.INFO); } saveProperties(); }
/** * Return the JSON data object from the URL. */ public Vertex requestJSON(String url, String attribute, Map<String, String> headers, Network network) { log("GET JSON", Level.INFO, url, attribute); try { String json = Utils.httpGET(url, headers); log("JSON", Level.FINE, json); JSON root = (JSON)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Object value = root; if (attribute != null) { value = ((JSONObject)root).get(attribute); if (value == null) { return null; } } Vertex object = convertElement(value, network); return object; } catch (Exception exception) { log(exception); return null; } }
/** * Return the count of the JSON result array. */ public int countJSON(String url, String attribute, Network network) { log("COUNT JSON", Level.INFO, url, attribute); try { String json = Utils.httpGET(url); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return 0; } Object value = root.get(attribute); if (value == null) { return 0; } if (value instanceof JSONArray) { return ((JSONArray)value).size(); } return 1; } catch (Exception exception) { log(exception); return 0; } }
/** * POST the JSON object and return the JSON data from the URL. */ public Vertex postJSON(String url, Vertex jsonObject, Network network) { log("POST JSON", Level.INFO, url); try { String data = convertToJSON(jsonObject); log("POST JSON", Level.FINE, data); String json = Utils.httpPOST(url, "application/json", data); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = convertElement(root, network); return object; } catch (Exception exception) { log(exception); return null; } }
/** * PUT the JSON object and return the JSON data from the URL. */ public Vertex putJSON(String url, Vertex jsonObject, Network network) { log("PUT JSON", Level.INFO, url); try { String data = convertToJSON(jsonObject); log("PUT JSON", Level.FINE, data); String json = Utils.httpPUT(url, "application/json", data); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = convertElement(root, network); return object; } catch (Exception exception) { log(exception); return null; } }
/** * Post the JSON object and return the JSON data from the URL. */ public Vertex postJSONAuth(String url, String user, String password, Vertex jsonObject, Network network) { log("POST JSON Auth", Level.INFO, url); try { String data = convertToJSON(jsonObject); log("POST JSON", Level.FINE, data); String json = Utils.httpAuthPOST(url, user, password, "application/json", data); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = convertElement(root, network); return object; } catch (Exception exception) { log(exception); return null; } }
/** * Post the JSON object and return the JSON data from the URL. */ public Vertex postJSONAuth(String url, String user, String password, String agent, Vertex jsonObject, Network network) { log("POST JSON Auth", Level.INFO, url); try { String data = convertToJSON(jsonObject); log("POST JSON", Level.FINE, data); String json = Utils.httpAuthPOST(url, user, password, agent, "application/json", data); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = convertElement(root, network); return object; } catch (Exception exception) { log(exception); return null; } }
/** * GET the JSON data from the URL. */ public Vertex requestJSONAuth(String url, String user, String password, Network network) { log("GET JSON Auth", Level.INFO, url); try { String json = Utils.httpAuthGET(url, user, password); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = convertElement(root, network); return object; } catch (Exception exception) { log(exception); return null; } }
/** * GET the JSON data from the URL. */ public Vertex requestJSONAuth(String url, String user, String password, String agent, Network network) { log("GET JSON Auth", Level.INFO, url); try { String json = Utils.httpAuthGET(url, user, password, agent); log("JSON", Level.FINE, json); JSONObject root = (JSONObject)JSONSerializer.toJSON(json.trim()); if (root == null) { return null; } Vertex object = convertElement(root, network); return object; } catch (Exception exception) { log(exception); return null; } }