List of usage examples for java.net URL toString
public String toString()
From source file:com.mycompany.kerberosbyip.NewMain.java
public static void main(String[] args) throws Exception { Logger logger = Logger.getLogger("org.apache.http"); logger.setLevel(Level.TRACE); System.setProperty("sun.security.krb5.debug", "true"); System.setProperty("java.security.krb5.realm", REALM); System.setProperty("java.security.krb5.kdc", KDC); ClassLoader classLoader = NewMain.class.getClassLoader(); URL loginConf = classLoader.getResource("login.conf"); System.setProperty("java.security.auth.login.config", loginConf.toString()); NewMain m = new NewMain(); m.runPrivileged();//ww w. j a v a2 s. c om }
From source file:io.apiman.servers.gateway_h2.Starter.java
/** * Main entry point for the API Gateway micro service. * @param args the arguments/*from w ww . j a v a 2s. c o m*/ * @throws Exception when any unhandled exception occurs */ public static final void main(String[] args) throws Exception { URL resource = Starter.class.getClassLoader().getResource("users.list"); //$NON-NLS-1$ if (resource != null) { System.setProperty(Users.USERS_FILE_PROP, resource.toString()); } createDataSource(); loadProperties(); GatewayMicroService microService = new GatewayMicroService(); microService.start(); microService.join(); }
From source file:ratpack.spark.jobserver.Main.java
public static void main(String... args) throws Exception { RatpackServer ratpackServer = RatpackServer.start(spec -> spec.serverConfig(builder -> { Path basePath = BaseDir.find("application.properties"); LOGGER.debug("BASE DIR: {}", basePath.toString()); builder.baseDir(BaseDir.find("application.properties")).env().sysProps(); Path localAppProps = Paths.get("../../config/application.properties"); if (Files.exists(localAppProps)) { LOGGER.debug("LOCALLY OVERLOADED application.properties: {}", localAppProps.toUri().toString()); builder.props(localAppProps); } else {// www .ja v a 2 s . com URL cpAppProps = Main.class.getClassLoader().getResource("config/application.properties"); LOGGER.debug("CLASSPATH OVERLOADED application.properties: {}", cpAppProps != null ? cpAppProps.toString() : "DEFAULT LOCATION"); builder.props(cpAppProps != null ? cpAppProps : Main.class.getClassLoader().getResource("application.properties")); } Path localSparkJobsProps = Paths.get("../../config/sparkjobs.properties"); if (Files.exists(localSparkJobsProps)) { LOGGER.debug("LOCALLY OVERLOADED sparkjobs.properties: {}", localSparkJobsProps.toUri().toString()); builder.props(localSparkJobsProps); } else { URL cpSparkJobsProps = Main.class.getClassLoader().getResource("config/sparkjobs.properties"); LOGGER.debug("CLASSPATH OVERLOADED SPARKJOBS.PROPS: {}", cpSparkJobsProps != null ? cpSparkJobsProps.toString() : "DEFAULT LOCATION"); builder.props(cpSparkJobsProps != null ? cpSparkJobsProps : Main.class.getClassLoader().getResource("sparkjobs.properties")); } builder.require("/spark", SparkConfig.class).require("/job", SparkJobsConfig.class); }).registry(Guice.registry(bindingsSpec -> bindingsSpec.bindInstance(ResponseTimer.decorator()) .module(ContainersModule.class).module(SparkModule.class) .bindInstance(new ObjectMapper().writerWithDefaultPrettyPrinter()))) .handlers(chain -> chain.all(ctx -> { LOGGER.debug("ALL"); MDC.put("clientIP", ctx.getRequest().getRemoteAddress().getHostText()); RequestId.Generator generator = ctx.maybeGet(RequestId.Generator.class) .orElse(UuidBasedRequestIdGenerator.INSTANCE); RequestId requestId = generator.generate(ctx.getRequest()); ctx.getRequest().add(RequestId.class, requestId); MDC.put("requestId", requestId.toString()); ctx.next(); }).prefix("v1", chain1 -> chain1.all(RequestLogger.ncsa()).get("api-def", ctx -> { LOGGER.debug("GET API_DEF.JSON"); SparkJobsConfig config = ctx.get(SparkJobsConfig.class); LOGGER.debug("SPARK JOBS CONFIG: " + config.toString()); ctx.render(ctx.file("public/apidef/apidef.json")); }).prefix("spark", JobsEndpoints.class)))); LOGGER.debug("STARTED: {}://{}:{}", ratpackServer.getScheme(), ratpackServer.getBindHost(), ratpackServer.getBindPort()); }
From source file:com.gemini.httpclienttest.HttpClientTestMain.java
public static void main(String[] args) { //authenticate with the server URL url; try {/* w w w. j a v a2 s .co m*/ url = new URL("http://198.11.209.34:5000/v2.0/tokens"); } catch (MalformedURLException ex) { System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0"); return; } CloseableHttpClient httpclient = HttpClientBuilder.create().build(); try { HttpPost httpPost = new HttpPost(url.toString()); httpPost.setHeader("Content-Type", "application/json"); StringEntity strEntity = new StringEntity( "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}"); httpPost.setEntity(strEntity); //System.out.println("Executing request " + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpPost); try { //get the response status code String respStatus = response.getStatusLine().getReasonPhrase(); //get the response body int bytes = response.getEntity().getContent().available(); InputStream body = response.getEntity().getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(body)); String line; StringBuffer sbJSON = new StringBuffer(); while ((line = in.readLine()) != null) { sbJSON.append(line); } String json = sbJSON.toString(); EntityUtils.consume(response.getEntity()); GsonBuilder gsonBuilder = new GsonBuilder(); Object parsedJson = gsonBuilder.create().fromJson(json, Object.class); System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString()); if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) { com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson; if (treeJson.containsKey("id")) { String s = (String) treeJson.getOrDefault("id", "no key provided"); System.out.printf("\n\ntree contained id %s\n", s); } else { System.out.printf("\n\ntree does not contain key id\n"); } } } catch (IOException ex) { System.out.print(ex); } finally { response.close(); } } catch (IOException ex) { System.out.print(ex); } finally { //lots of exceptions, just the connection and exit try { httpclient.close(); } catch (IOException | NoSuchMethodError ex) { System.out.print(ex); return; } } }
From source file:io.amient.kafka.metrics.DiscoveryTool.java
public static void main(String[] args) throws IOException { OptionParser parser = new OptionParser(); parser.accepts("help", "Print usage help"); OptionSpec<String> zookeeper = parser.accepts("zookeeper", "Address of the seed zookeeper server") .withRequiredArg().required(); OptionSpec<String> dashboard = parser .accepts("dashboard", "Grafana dashboard name to be used in all generated configs") .withRequiredArg().required(); OptionSpec<String> dashboardPath = parser .accepts("dashboard-path", "Grafana location, i.e. `./instance/.data/grafana/dashboards`") .withRequiredArg();/* w ww.j a va 2s.c om*/ OptionSpec<String> topic = parser.accepts("topic", "Name of the metrics topic to consume measurements from") .withRequiredArg(); OptionSpec<String> influxdb = parser .accepts("influxdb", "InfluxDB connect URL (including user and password)").withRequiredArg(); OptionSpec<String> interval = parser.accepts("interval", "JMX scanning interval in seconds") .withRequiredArg().defaultsTo("10"); //TODO --influxdb-database (DEFAULT_DATABASE) //TODO --dashboard-datasource (DEFAULT_DATASOURCE) if (args.length == 0 || args[0] == "-h" || args[0] == "--help") { parser.printHelpOn(System.err); System.exit(0); } OptionSet opts = parser.parse(args); try { DiscoveryTool tool = new DiscoveryTool(opts.valueOf(zookeeper)); try { List<String> topics = tool.getKafkaTopics(); List<Broker> brokers = tool.getKafkaBrokers(); int interval_s = Integer.parseInt(opts.valueOf(interval)); if (opts.has(dashboard) && opts.has(dashboardPath)) { tool.generateDashboard(opts.valueOf(dashboard), brokers, topics, DEFAULT_DATASOURCE, opts.valueOf(dashboardPath), interval_s).save(); } if (opts.has(topic)) { //producer/reporter settings System.out.println("kafka.metrics.topic=" + opts.valueOf(topic)); System.out.println("kafka.metrics.polling.interval=" + interval_s + "s"); //TODO --producer-bootstrap for truly non-intrusive agent deployment, // i.e. when producing to a different cluster from the one being discovered System.out.println("kafka.metrics.bootstrap.servers=" + brokers.get(0).hostPort()); //consumer settings System.out.println("consumer.topic=" + opts.valueOf(topic)); System.out.println("consumer.zookeeper.connect=" + opts.valueOf(zookeeper)); System.out.println("consumer.group.id=kafka-metrics-" + opts.valueOf(dashboard)); } if (!opts.has(influxdb) || !opts.has(topic)) { tool.generateScannerConfig(brokers, opts.valueOf(dashboard), interval_s).list(System.out); } if (opts.has(influxdb)) { URL url = new URL(opts.valueOf(influxdb)); System.out.println("influxdb.database=" + DEFAULT_DATABASE); System.out.println("influxdb.url=" + url.toString()); if (url.getUserInfo() != null) { System.out.println("influxdb.username=" + url.getUserInfo().split(":")[0]); if (url.getUserInfo().contains(":")) { System.out.println("influxdb.password=" + url.getUserInfo().split(":")[1]); } } } System.out.flush(); } catch (IOException e) { e.printStackTrace(); System.exit(3); } finally { tool.close(); } } catch (Exception e) { e.printStackTrace(); System.exit(2); } }
From source file:MainClass.java
public static void main(String argv[]) { java.net.URL u = null; try {/*from w w w .j ava 2 s.c o m*/ u = new java.net.URL("http://www.java2s.com/"); } catch (java.net.MalformedURLException ignored) { } JFormattedTextField ftf1 = new JFormattedTextField(u); JFormattedTextField ftf2 = new JFormattedTextField(u); ftf2.setInputVerifier(new InputVerifier() { public boolean verify(JComponent input) { if (!(input instanceof JFormattedTextField)) return true; return ((JFormattedTextField) input).isEditValid(); } }); JPanel p = new JPanel(new GridLayout(0, 2, 3, 8)); p.add(new JLabel("plain JFormattedTextField:")); p.add(ftf1); p.add(new JLabel("FTF with InputVerifier:")); p.add(ftf2); p.add(new JLabel("plain JTextField:")); p.add(new JTextField(u.toString())); JFrame f = new JFrame("MainClass"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(new JLabel("Try to delete the colon in each field."), "North"); f.getContentPane().add(p, "Center"); f.pack(); f.setVisible(true); }
From source file:FtfInputVerifier.java
public static void main(String argv[]) { java.net.URL u = null; try {/*from w ww . jav a2 s .com*/ u = new java.net.URL("http://www.ora.com/"); } catch (java.net.MalformedURLException ignored) { } // create two identical JFormattedTextFields JFormattedTextField ftf1 = new JFormattedTextField(u); JFormattedTextField ftf2 = new JFormattedTextField(u); // and set an InputVerifier on one of them ftf2.setInputVerifier(new InputVerifier() { public boolean verify(JComponent input) { if (!(input instanceof JFormattedTextField)) return true; // give up focus return ((JFormattedTextField) input).isEditValid(); } }); JPanel p = new JPanel(new java.awt.GridLayout(0, 2, 3, 8)); p.add(new JLabel("plain JFormattedTextField:", JLabel.RIGHT)); p.add(ftf1); p.add(new JLabel("FTF with InputVerifier:", JLabel.RIGHT)); p.add(ftf2); p.add(new JLabel("plain JTextField:", JLabel.RIGHT)); p.add(new JTextField(u.toString())); p.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); JFrame f = new JFrame("FtfInputVerifier"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(new JLabel("Try to delete the colon in each field.", JLabel.CENTER), java.awt.BorderLayout.NORTH); f.getContentPane().add(p, java.awt.BorderLayout.CENTER); f.pack(); f.setVisible(true); }
From source file:eu.clarin.cmdi.vlo.importer.MetadataImporter.java
/** * @param args/*from ww w . ja v a2 s .co m*/ * @throws MalformedURLException * @throws IOException */ public static void main(String[] args) throws MalformedURLException, IOException { // path to the configuration file String configFile = null; // use the Apache cli framework for getting command line parameters Options options = new Options(); // Data root list passed from command line with -l option String cldrList = null; /** * Add a "c" option, the option indicating the specification of an XML * configuration file * * "l" option - to specify which data roots (from config file) to import * imports all by default */ options.addOption("c", true, "-c <file> : use parameters specified in <file>"); options.addOption("l", true, "-l <dataroot> [ ' ' <dataroot> ]* : space separated list of dataroots to be processed.\n" + "If dataroot is not specified in config file it will be ignored."); options.getOption("l").setOptionalArg(true); CommandLineParser parser = new PosixParser(); try { // parse the command line arguments CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("c")) { // the "c" option was specified, now get its value configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("l")) { cldrList = cmd.getOptionValue("l"); } } catch (org.apache.commons.cli.ParseException ex) { /** * Caught an exception caused by command line parsing. Try to get * the name of the configuration file by querying the system * property. */ String message = "Command line parsing failed. " + ex.getMessage(); LOG.error(message); System.err.println(message); } if (configFile == null) { String message; message = "Could not get config file name via the command line, trying the system properties."; LOG.info(message); String key; key = "configFile"; configFile = System.getProperty(key); } if (configFile == null) { String message; message = "Could not get filename as system property either - stopping."; LOG.error(message); } else { // read the configuration from the externally supplied file final URL configUrl; if (configFile.startsWith("file:")) { configUrl = new URL(configFile); } else { configUrl = new File(configFile).toURI().toURL(); } System.out.println("Reading configuration from " + configUrl.toString()); LOG.info("Reading configuration from " + configUrl.toString()); final XmlVloConfigFactory configFactory = new XmlVloConfigFactory(configUrl); MetadataImporter.config = configFactory.newConfig(); MetadataImporter.languageCodeUtils = new LanguageCodeUtils(MetadataImporter.config); // optionally, modify the configuration here // create and start the importer MetadataImporter importer = new MetadataImporter(cldrList); importer.startImport(); // finished importing if (MetadataImporter.config.printMapping()) { File file = new File("xsdMapping.txt"); FacetMappingFactory.printMapping(file); LOG.info("Printed facetMapping in " + file); } } }
From source file:com.sforce.dataset.DatasetUtilMain.java
public static void main(String[] args) { printBanner();//from w ww.j a v a2s. co m DatasetUtilParams params = new DatasetUtilParams(); if (args.length > 0) params.server = false; System.out.println(""); System.out.println("DatsetUtils called with {" + args.length + "} Params:"); for (int i = 0; i < args.length; i++) { if ((i & 1) == 0) { System.out.print("{" + args[i] + "}"); } else { if (i > 0 && args[i - 1].equalsIgnoreCase("--p")) System.out.println(":{*******}"); else System.out.println(":{" + args[i] + "}"); } if (i > 0 && args[i - 1].equalsIgnoreCase("--server")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("false")) params.server = false; else if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.server = true; } } System.out.println(""); if (!printlneula(params.server)) { System.out.println( "You do not have permission to use this software. Please delete it from this computer"); System.exit(-1); } String action = null; if (args.length >= 2) { for (int i = 1; i < args.length; i = i + 2) { if (args[i - 1].equalsIgnoreCase("--help") || args[i - 1].equalsIgnoreCase("-help") || args[i - 1].equalsIgnoreCase("help")) { printUsage(); } else if (args[i - 1].equalsIgnoreCase("--u")) { params.username = args[i]; } else if (args[i - 1].equalsIgnoreCase("--p")) { params.password = args[i]; } else if (args[i - 1].equalsIgnoreCase("--sessionId")) { params.sessionId = args[i]; } else if (args[i - 1].equalsIgnoreCase("--token")) { params.token = args[i]; } else if (args[i - 1].equalsIgnoreCase("--endpoint")) { params.endpoint = args[i]; } else if (args[i - 1].equalsIgnoreCase("--action")) { action = args[i]; } else if (args[i - 1].equalsIgnoreCase("--operation")) { if (args[i] != null) { if (args[i].equalsIgnoreCase("overwrite")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("upsert")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("append")) { params.Operation = args[i]; } else if (args[i].equalsIgnoreCase("delete")) { params.Operation = args[i]; } else { System.out.println("Invalid Operation {" + args[i] + "} Must be Overwrite or Upsert or Append or Delete"); System.exit(-1); } } } else if (args[i - 1].equalsIgnoreCase("--debug")) { params.debug = true; DatasetUtilConstants.debug = true; } else if (args[i - 1].equalsIgnoreCase("--ext")) { DatasetUtilConstants.ext = true; } else if (args[i - 1].equalsIgnoreCase("--inputFile")) { String tmp = args[i]; if (tmp != null) { File tempFile = new File(tmp); if (tempFile.exists()) { params.inputFile = tempFile.toString(); } else { System.out.println("File {" + args[i] + "} does not exist"); System.exit(-1); } } } else if (args[i - 1].equalsIgnoreCase("--dataset")) { params.dataset = args[i]; } else if (args[i - 1].equalsIgnoreCase("--datasetLabel")) { params.datasetLabel = args[i]; } else if (args[i - 1].equalsIgnoreCase("--app")) { params.app = args[i]; } else if (args[i - 1].equalsIgnoreCase("--useBulkAPI")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.useBulkAPI = true; } else if (args[i - 1].equalsIgnoreCase("--uploadFormat")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("csv")) params.uploadFormat = "csv"; else if (args[i] != null && args[i].trim().equalsIgnoreCase("binary")) params.uploadFormat = "binary"; } else if (args[i - 1].equalsIgnoreCase("--rowLimit")) { if (args[i] != null && !args[i].trim().isEmpty()) params.rowLimit = (new BigDecimal(args[i].trim())).intValue(); } else if (args[i - 1].equalsIgnoreCase("--rootObject")) { params.rootObject = args[i]; } else if (args[i - 1].equalsIgnoreCase("--fileEncoding")) { params.fileEncoding = args[i]; } else if (args[i - 1].equalsIgnoreCase("--server")) { if (args[i] != null && args[i].trim().equalsIgnoreCase("true")) params.server = true; else if (args[i] != null && args[i].trim().equalsIgnoreCase("false")) params.server = false; } else if (args[i - 1].equalsIgnoreCase("--codingErrorAction")) { if (args[i] != null) { if (args[i].equalsIgnoreCase("IGNORE")) { params.codingErrorAction = CodingErrorAction.IGNORE; } else if (args[i].equalsIgnoreCase("REPORT")) { params.codingErrorAction = CodingErrorAction.REPORT; } else if (args[i].equalsIgnoreCase("REPLACE")) { params.codingErrorAction = CodingErrorAction.REPLACE; } } } else { printUsage(); System.out.println("\nERROR: Invalid argument: " + args[i - 1]); System.exit(-1); } } //end for if (params.username != null) { if (params.endpoint == null || params.endpoint.isEmpty()) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } } } if (params.server) { System.out.println(); System.out.println("\n*******************************************************************************"); try { DatasetUtilServer datasetUtilServer = new DatasetUtilServer(); datasetUtilServer.init(args, true); } catch (Exception e) { e.printStackTrace(); } System.out.println("Server ended, exiting JVM....."); System.out.println("*******************************************************************************\n"); System.out.println("QUITAPP"); System.exit(0); } if (params.sessionId == null) { if (params.username == null || params.username.trim().isEmpty()) { params.username = getInputFromUser("Enter salesforce username: ", true, false); } if (params.username.equals("-1")) { params.sessionId = getInputFromUser("Enter salesforce sessionId: ", true, false); params.username = null; params.password = null; } else { if (params.password == null || params.password.trim().isEmpty()) { params.password = getInputFromUser("Enter salesforce password: ", true, true); } } } if (params.sessionId != null && !params.sessionId.isEmpty()) { while (params.endpoint == null || params.endpoint.trim().isEmpty()) { params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false); if (params.endpoint == null || params.endpoint.trim().isEmpty()) System.out.println("\nERROR: endpoint must be specified when sessionId is specified"); } while (params.endpoint.toLowerCase().contains("login.salesforce.com") || params.endpoint.toLowerCase().contains("test.salesforce.com") || params.endpoint.toLowerCase().contains("test") || params.endpoint.toLowerCase().contains("prod") || params.endpoint.toLowerCase().contains("sandbox")) { System.out.println("\nERROR: endpoint must be the actual serviceURL and not the login url"); params.endpoint = getInputFromUser("Enter salesforce instance url: ", true, false); } } else { if (params.endpoint == null || params.endpoint.isEmpty()) { params.endpoint = getInputFromUser("Enter salesforce instance url (default=prod): ", false, false); if (params.endpoint == null || params.endpoint.trim().isEmpty()) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } } } try { if (params.endpoint.equalsIgnoreCase("PROD") || params.endpoint.equalsIgnoreCase("PRODUCTION")) { params.endpoint = DatasetUtilConstants.defaultEndpoint; } else if (params.endpoint.equalsIgnoreCase("TEST") || params.endpoint.equalsIgnoreCase("SANDBOX")) { params.endpoint = DatasetUtilConstants.defaultEndpoint.replace("login", "test"); } URL uri = new URL(params.endpoint); String protocol = uri.getProtocol(); String host = uri.getHost(); if (protocol == null || !protocol.equalsIgnoreCase("https")) { if (host == null || !(host.toLowerCase().endsWith("internal.salesforce.com") || host.toLowerCase().endsWith("localhost"))) { System.out.println("\nERROR: Invalid endpoint. UNSUPPORTED_CLIENT: HTTPS Required in endpoint"); System.exit(-1); } } if (uri.getPath() == null || uri.getPath().isEmpty() || uri.getPath().equals("/")) { uri = new URL(uri.getProtocol(), uri.getHost(), uri.getPort(), DatasetUtilConstants.defaultSoapEndPointPath); } params.endpoint = uri.toString(); } catch (MalformedURLException e) { e.printStackTrace(); System.out.println("\nERROR: endpoint is not a valid URL"); System.exit(-1); } PartnerConnection partnerConnection = null; if (params.username != null || params.sessionId != null) { try { partnerConnection = DatasetUtils.login(0, params.username, params.password, params.token, params.endpoint, params.sessionId, params.debug); } catch (ConnectionException e) { e.printStackTrace(); System.exit(-1); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(-1); } } if (args.length == 0 || action == null) { // System.out.println("\n*******************************************************************************"); //// FileListenerUtil.startAllListener(partnerConnection); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // } // System.out.println("*******************************************************************************\n"); // System.out.println(); // System.out.println("\n*******************************************************************************"); // try { // DatasetUtilServer datasetUtilServer = new DatasetUtilServer(); // datasetUtilServer.init(args, false); // } catch (Exception e) { // e.printStackTrace(); // } // System.out.println("*******************************************************************************\n"); // System.out.println(); while (true) { action = getActionFromUser(); if (action == null || action.isEmpty()) { System.exit(-1); } params = new DatasetUtilParams(); getRequiredParams(action, partnerConnection, params); @SuppressWarnings("unused") boolean status = doAction(action, partnerConnection, params); // if(status) // { // if(action.equalsIgnoreCase("load") && params.debug) // createListener(partnerConnection, params); // } } } else { doAction(action, partnerConnection, params); } }
From source file:JSON.JasonJSON.java
public static void main(String[] args) throws Exception { URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json"); //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground //writes a perfectly formatted JSON file that is easy to read with Java. // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201"); try {/* w w w . j a va 2s. c o m*/ HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection(); // This part will read the data returned thru HTTP and load it into memory // I have this code left over from my CIT260 project. InputStream stream = urlCon.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } // The next lines read certain parts of the JSON data and print it out on the screen //Creates the JSONObject object and loads the JSON file from the URLConnection //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something JSONObject json = new JSONObject(result.toString()); JSONObject coloradoInfo = (JSONObject) json.get("current_observation"); StringWriter out = new StringWriter(); json.write(out); String jsonTxt = json.toString(); System.out.print(jsonTxt); List<String> list = new ArrayList<>(); JSONArray array = json.getJSONArray(jsonTxt); System.out.print(jsonTxt); // for (int i =0;i<array.length();i++){ //list.add(array.getJSONObject(i).getString("current_observation")); //} String wunderGround = "Data downloaded from: " + coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: " + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: " + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: " + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: " + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: " + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: " + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: " + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string") + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: " + coloradoInfo.get("pressure_in"); System.out.println("\nColorado Springs Weather:"); System.out.println("____________________________________"); System.out.println(wunderGround); } catch (IOException e) { System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString() + "\nERROR: " + e.toString()); } }