List of usage examples for java.lang Exception getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:de.oth.keycloak.InitKeycloakServer.java
public static void main(String[] args) { CheckParams checkParams = CheckParams.create(args, System.out, InitKeycloakServer.class.getName()); if (checkParams == null) { System.exit(1);/*from w w w . ja v a 2s .c om*/ } try { String server = checkParams.getServer(); String realm = checkParams.getRealm(); String user = checkParams.getUser(); String pwd = checkParams.getPwd(); String clientStr = checkParams.getClient(); String secret = checkParams.getSecret(); String initFileStr = checkParams.getInitFile(); File initFile = new File(initFileStr); if (!initFile.isFile()) { URL url = InitKeycloakServer.class.getClassLoader().getResource(initFileStr); if (url != null) { initFile = new File(url.getFile()); if (!initFile.isFile()) { log.error("init file does not exist: " + initFile); System.exit(1); } } else { log.error("init file does not exist: " + initFile); System.exit(1); } } Keycloak keycloak = (secret == null) ? Keycloak.getInstance(server, realm, user, pwd, clientStr) : Keycloak.getInstance(server, realm, user, pwd, clientStr, secret); ObjectMapper mapper = new ObjectMapper(); RealmsConfig realmsConfig = mapper.readValue(initFile, RealmsConfig.class); if (realmsConfig != null) { List<RealmConfig> realmList = realmsConfig.getRealms(); if (realmList == null || realmList.isEmpty()) { log.error("no realms config found 1"); return; } for (RealmConfig realmConf : realmList) { addRealm(keycloak, realmConf); } } else { log.error("no realms config found 2"); } } catch (Exception e) { log.error(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); System.exit(1); } }
From source file:org.atomserver.core.dbstore.utils.DBPurger.java
public static void main(String[] args) { if (args.length < 1 || args.length > 2) { throw new IllegalArgumentException("args.length < 1 || args.length > 2"); }/* w w w. j a v a 2 s. c o m*/ String workspace = args[0]; String collection = null; if (args.length == 2) { collection = args[1]; } if (log.isDebugEnabled()) log.debug("workspace= " + workspace + " collection= " + collection); try { getInstance().purge(workspace, collection); } catch (Exception ee) { System.out.println("Exception = " + ee.getClass().getName() + " message= " + ee.getMessage()); ee.printStackTrace(); System.out.println("Could NOT purge " + workspace + " " + collection); System.exit(123); } }
From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java
public static void main(String[] args) { Scanner scan = new Scanner(System.in); loadConfig();//from ww w.j a v a 2s . c o m AlphonseBot bot = new AlphonseBot(nick, pass, server, channels, maxXKCD, noVoiceNicks, masters, dadLeaveTimes); bot.setMessageDelay(500); try { bot.startConnection(); } catch (IOException | IrcException ex) { Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex); } boolean quit = false; while (!quit) { String curLine = scan.nextLine(); switch (curLine) { case "exit": System.out.println("Quitting."); bot.onPreQuit(); bot.disconnect(); bot.dispose(); writeConfig(); quit = true; System.out.println("Quit'd."); break; case "msg": Scanner lineScan = new Scanner(scan.nextLine()); try { bot.sendMessage(lineScan.next(), lineScan.nextLine()); } catch (Exception e) { System.err.println(e.getClass().toString()); System.err.println("Not enough args"); } break; default: System.out.println("Invalid command."); } } }
From source file:net.modelbased.proasense.storage.reader.StorageReaderScrapRateTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageReaderMongoServiceTestClient client = new StorageReaderMongoServiceTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_READER_SERVICE_URL = "http://192.168.84.34:8080/storage-reader"; String QUERY_SIMPLE_SENSORID = "1000692"; String QUERY_SIMPLE_STARTTIME = "1387565891068"; String QUERY_SIMPLE_ENDTIME = "1387565996633"; String QUERY_SIMPLE_PROPERTYKEY = "value"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;// w w w . j ava 2s .co m // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); response = client.execute(query11); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.DEFAULT: " + body); // The result is an array of simple events serialized as JSON using Apache Thrift. // The simple events can be deserialized into Java objects using Apache Thrift. ObjectMapper mapper = new ObjectMapper(); JsonNode nodeArray = mapper.readTree(body); for (JsonNode node : nodeArray) { byte[] bytes = node.toString().getBytes(); TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory()); SimpleEvent event = new SimpleEvent(); deserializer.deserialize(event, bytes); System.out.println(event.toString()); } } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/average"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query12 = new HttpGet(requestUrl.toString()); query12.setHeader("Content-type", "application/json"); response = client.execute(query12); // Get status code status = response.getStatusLine().getStatusCode(); if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.AVERAGE: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/maximum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query13 = new HttpGet(requestUrl.toString()); query13.setHeader("Content-type", "application/json"); response = client.execute(query13); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MAXIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/minimum"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_SENSORID)); params.add(new BasicNameValuePair("startTime", QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", QUERY_SIMPLE_PROPERTYKEY)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query14 = new HttpGet(requestUrl.toString()); query14.setHeader("Content-type", "application/json"); response = client.execute(query14); // Get status code if (status == 200) { // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SIMPLE.MINIMUM: " + body); } else System.out.println("Error code: " + status); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:net.modelbased.proasense.storage.registry.StorageRegistryScrapRateTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageRegistryScrapRateTestClient client = new StorageRegistryScrapRateTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_REGISTRY_SERVICE_URL = "http://192.168.84.34:8080/storage-registry"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;// w w w . j a va2 s .com // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Query for machine list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/machine/list"); try { HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); response = client.execute(query11); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("MACHINE LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for machine properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/machine/list"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("machineId", "IMM1")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query12 = new HttpGet(requestUrl.toString()); query12.setHeader("Content-type", "application/json"); response = client.execute(query12); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("MACHINE PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for sensor list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/list"); try { HttpGet query21 = new HttpGet(requestUrl.toString()); query21.setHeader("Content-type", "application/json"); response = client.execute(query21); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SENSOR LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for sensor properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", "dustParticleSensor")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query22 = new HttpGet(requestUrl.toString()); query22.setHeader("Content-type", "application/json"); response = client.execute(query22); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SENSOR PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for product list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/list"); try { HttpGet query31 = new HttpGet(requestUrl.toString()); query31.setHeader("Content-type", "application/json"); response = client.execute(query31); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("PRODUCT LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for product properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("productId", "Astra_3300")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query22 = new HttpGet(requestUrl.toString()); query22.setHeader("Content-type", "application/json"); response = client.execute(query22); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("PRODUCT PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for mould list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/mould/list"); try { HttpGet query41 = new HttpGet(requestUrl.toString()); query41.setHeader("Content-type", "application/json"); response = client.execute(query41); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("MOULD LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for mould properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/product/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("productId", "Astra_3300")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query42 = new HttpGet(requestUrl.toString()); query42.setHeader("Content-type", "application/json"); response = client.execute(query42); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("MOULD PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.googlecode.flyway.commandline.Main.java
/** * Main method.//from www .j ava 2 s .c om * * @param args The command-line arguments. */ public static void main(String[] args) { boolean debug = isDebug(args); try { printVersion(); String operation = determineOperation(args); if (operation == null) { printUsage(); return; } loadJdbcDriversAndJavaMigrations(); Flyway flyway = new Flyway(); Properties properties = new Properties(); initializeDefaults(properties); loadConfigurationFile(properties, args); overrideConfiguration(properties, args); flyway.configure(properties); if ("clean".equals(operation)) { flyway.clean(); } else if ("init".equals(operation)) { flyway.init(); } else if ("migrate".equals(operation)) { flyway.migrate(); } else if ("validate".equals(operation)) { flyway.validate(); } else if ("status".equals(operation)) { MetaDataTableRowDumper.dumpMigration(flyway.status()); } else if ("history".equals(operation)) { MetaDataTableRowDumper.dumpMigrations(flyway.history()); } else { printUsage(); } } catch (Exception e) { if (debug) { LOG.error("Unexpected error", e); } else { LOG.error(ClassUtils.getShortName(e.getClass()) + ": " + e.getMessage()); outputFirstStackTraceElement(e); @SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" }) Throwable rootCause = ExceptionUtils.getRootCause(e); if (rootCause != null) { LOG.error("Caused by " + rootCause.toString()); outputFirstStackTraceElement(rootCause); } } System.exit(1); } }
From source file:net.modelbased.proasense.storage.reader.StorageReaderMongoServiceRestBenchmark.java
public static void main(String[] args) { // Get benchmark properties StorageReaderMongoServiceRestBenchmark benchmark = new StorageReaderMongoServiceRestBenchmark(); benchmark.loadClientProperties();//from w w w .jav a2s.co m // ProaSense Storage Reader Service configuration properties String STORAGE_READER_SERVICE_URL = benchmark.clientProperties .getProperty("proasense.storage.reader.service.url"); String QUERY_SIMPLE_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.collectionid"); String NO_QUERY_SIMPLE_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.starttime"); String NO_QUERY_SIMPLE_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.simple.endtime"); String QUERY_DERIVED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.collectionid"); String NO_QUERY_DERIVED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.starttime"); String NO_QUERY_DERIVED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.derived.endtime"); String QUERY_PREDICTED_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.collectionid"); String NO_QUERY_PREDICTED_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.starttime"); String NO_QUERY_PREDICTED_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.predicted.endtime"); String QUERY_ANOMALY_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.collectionid"); String NO_QUERY_ANOMALY_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.starttime"); String NO_QUERY_ANOMALY_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.anomaly.endtime"); String QUERY_RECOMMENDATION_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.collectionid"); String NO_QUERY_RECOMMENDATION_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.starttime"); String NO_QUERY_RECOMMENDATION_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.recommendation.endtime"); String QUERY_FEEDBACK_COLLECTIONID = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.collectionid"); String NO_QUERY_FEEDBACK_STARTTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.starttime"); String NO_QUERY_FEEDBACK_ENDTIME = benchmark.clientProperties .getProperty("proasense.benchmark.query.feedback.endtime"); String propertyKey = "value"; // Default HTTP client and common property variables for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null; StatusLine status = null; // Default query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/default"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query11 = new HttpGet(requestUrl.toString()); query11.setHeader("Content-type", "application/json"); try { status = client.execute(query11).getStatusLine(); System.out.println("SIMPLE.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for simple events requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL); requestUrl.append("/query/simple/value"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID)); params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME)); params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME)); params.add(new BasicNameValuePair("propertyKey", "value")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); HttpGet query12 = new HttpGet(STORAGE_READER_SERVICE_URL); query12.setHeader("Content-type", "application/json"); try { status = client.execute(query12).getStatusLine(); System.out.println("SIMPLE.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for simple events HttpGet query13 = new HttpGet(STORAGE_READER_SERVICE_URL); query13.setHeader("Content-type", "application/json"); try { status = client.execute(query13).getStatusLine(); System.out.println("SIMPLE.MAXIMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for simple events HttpGet query14 = new HttpGet(STORAGE_READER_SERVICE_URL); query14.setHeader("Content-type", "application/json"); try { status = client.execute(query14).getStatusLine(); System.out.println("SIMPLE.MINUMUM:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for derived events HttpGet query21 = new HttpGet(STORAGE_READER_SERVICE_URL); query21.setHeader("Content-type", "application/json"); try { status = client.execute(query21).getStatusLine(); System.out.println("DERIVED.DEFAULT:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for derived events HttpGet query22 = new HttpGet(STORAGE_READER_SERVICE_URL); query22.setHeader("Content-type", "application/json"); try { status = client.execute(query22).getStatusLine(); System.out.println("DERIVED.AVERAGE:" + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query23 = new HttpGet(STORAGE_READER_SERVICE_URL); query23.setHeader("Content-type", "application/json"); try { status = client.execute(query23).getStatusLine(); System.out.println("DERIVED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query24 = new HttpGet(STORAGE_READER_SERVICE_URL); query24.setHeader("Content-type", "application/json"); try { status = client.execute(query24).getStatusLine(); System.out.println("DERIVED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for predicted events HttpGet query31 = new HttpGet(STORAGE_READER_SERVICE_URL); query31.setHeader("Content-type", "application/json"); try { status = client.execute(query31).getStatusLine(); System.out.println("PREDICTED.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for predicted events HttpGet query32 = new HttpGet(STORAGE_READER_SERVICE_URL); query32.setHeader("Content-type", "application/json"); try { status = client.execute(query32).getStatusLine(); System.out.println("PREDICTED.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for predicted events HttpGet query33 = new HttpGet(STORAGE_READER_SERVICE_URL); query33.setHeader("Content-type", "application/json"); try { status = client.execute(query33).getStatusLine(); System.out.println("PREDICTED.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query34 = new HttpGet(STORAGE_READER_SERVICE_URL); query34.setHeader("Content-type", "application/json"); try { status = client.execute(query34).getStatusLine(); System.out.println("PREDICTED.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for anomaly events HttpGet query41 = new HttpGet(STORAGE_READER_SERVICE_URL); query41.setHeader("Content-type", "application/json"); try { status = client.execute(query41).getStatusLine(); System.out.println("ANOMALY.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for recommendation events HttpGet query51 = new HttpGet(STORAGE_READER_SERVICE_URL); query51.setHeader("Content-type", "application/json"); try { status = client.execute(query51).getStatusLine(); System.out.println("RECOMMENDATION.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Average query for recommendation events HttpGet query52 = new HttpGet(STORAGE_READER_SERVICE_URL); query52.setHeader("Content-type", "application/json"); try { status = client.execute(query52).getStatusLine(); System.out.println("RECOMMENDATION.AVERAGE: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Maximum query for derived events HttpGet query53 = new HttpGet(STORAGE_READER_SERVICE_URL); query53.setHeader("Content-type", "application/json"); try { status = client.execute(query53).getStatusLine(); System.out.println("RECOMMENDATION.MAXIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Minimum query for derived events HttpGet query54 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("RECOMMENDATION.MINIMUM: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Default query for feedback events HttpGet query61 = new HttpGet(STORAGE_READER_SERVICE_URL); query54.setHeader("Content-type", "application/json"); try { status = client.execute(query54).getStatusLine(); System.out.println("FEEDBACK.DEFAULT: " + status.toString()); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:bear.core.BearMain.java
/** * -VbearMain.appConfigDir=src/main/groovy/examples -VbearMain.buildDir=.bear/classes -VbearMain.script=dumpSampleGrid -VbearMain.projectClass=SecureSocialDemoProject -VbearMain.propertiesFile=.bear/test.properties *//*from ww w . j a v a 2 s.c o m*/ public static void main(String[] args) throws Exception { int i = ArrayUtils.indexOf(args, "--log-level"); if (i != -1) { LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.toLevel(args[i + 1])); } i = ArrayUtils.indexOf(args, "-q"); if (i != -1) { LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN); } GlobalContext global = GlobalContext.getInstance(); BearMain bearMain = null; try { bearMain = new BearMain(global, getCompilerManager(), args); } catch (Exception e) { if (e.getClass().getSimpleName().equals("MissingRequiredOptionException")) { System.out.println(e.getMessage()); } else { Throwables.getRootCause(e).printStackTrace(); } System.exit(-1); } if (bearMain.checkHelpAndVersion()) { return; } AppOptions2 options2 = bearMain.options; if (options2.has(AppOptions2.UNPACK_DEMOS)) { String filesAsText = ProjectGenerator.readResource("/demoFiles.txt"); int count = 0; for (String resource : filesAsText.split("::")) { File dest = new File(BEAR_DIR + resource); System.out.printf("copying %s to %s...%n", resource, dest); writeStringToFile(dest, ProjectGenerator.readResource(resource)); count++; } System.out.printf("extracted %d files%n", count); return; } if (options2.has(AppOptions2.CREATE_NEW)) { String dashedTitle = options2.get(AppOptions2.CREATE_NEW); String user = options2.get(AppOptions2.USER); String pass = options2.get(AppOptions2.PASSWORD); List<String> hosts = options2.getList(AppOptions2.HOSTS); List<String> template; if (options2.has(AppOptions2.TEMPLATE)) { template = options2.getList(AppOptions2.TEMPLATE); } else { template = emptyList(); } ProjectGenerator g = new ProjectGenerator(dashedTitle, user, pass, hosts, template); if (options2.has(AppOptions2.ORACLE_USER)) { g.oracleUser = options2.get(AppOptions2.ORACLE_USER); } if (options2.has(AppOptions2.ORACLE_PASSWORD)) { g.oraclePassword = options2.get(AppOptions2.ORACLE_PASSWORD); } File projectFile = new File(BEAR_DIR, g.getProjectTitle() + ".groovy"); File pomFile = new File(BEAR_DIR, "pom.xml"); writeStringToFile(projectFile, g.processTemplate("TemplateProject.template")); writeStringToFile(new File(BEAR_DIR, dashedTitle + ".properties"), g.processTemplate("project-properties.template")); writeStringToFile(new File(BEAR_DIR, "demos.properties"), g.processTemplate("project-properties.template")); writeStringToFile(new File(BEAR_DIR, "bear-fx.properties"), g.processTemplate("bear-fx.properties.template")); writeStringToFile(pomFile, g.generatePom(dashedTitle)); System.out.printf("Created project file: %s%n", projectFile.getPath()); System.out.printf("Created maven pom: %s%n", pomFile.getPath()); System.out.println("\nProject files have been created. You may now: " + "\n a) Run `bear " + g.getShortName() + ".ls` to quick-test your minimal setup" + "\n b) Import the project to IDE or run smoke tests, find more details at the project wiki: https://github.com/chaschev/bear/wiki/."); return; } Bear bear = global.bear; if (options2.has(AppOptions2.QUIET)) { global.put(bear.quiet, true); LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN); } if (options2.has(AppOptions2.USE_UI)) { global.put(bear.useUI, true); } if (options2.has(AppOptions2.NO_UI)) { global.put(bear.useUI, false); } List<?> list = options2.getOptionSet().nonOptionArguments(); if (list.size() > 1) { throw new IllegalArgumentException("too many arguments: " + list + ", " + "please specify an invoke line, project.method(arg1, arg2)"); } if (list.isEmpty()) { throw new UnsupportedOperationException("todo implement running a single project"); } String invokeLine = (String) list.get(0); String projectName; String method; if (invokeLine.contains(".")) { projectName = StringUtils.substringBefore(invokeLine, "."); method = StringUtils.substringAfter(invokeLine, "."); } else { projectName = invokeLine; method = null; } if (method == null || method.isEmpty()) method = "deploy()"; if (!method.contains("(")) method += "()"; Optional<CompiledEntry<? extends BearProject>> optional = bearMain.compileManager.findProject(projectName); if (!optional.isPresent()) { throw new IllegalArgumentException("project was not found: " + projectName + ", loaded classes: \n" + Joiner.on("\n").join(bearMain.compileManager.findProjects()) + ", searched in: " + bearMain.compileManager.getSourceDirs() + ", "); } BearProject project = OpenBean.newInstance(optional.get().aClass).injectMain(bearMain); GroovyShell shell = new GroovyShell(); shell.setVariable("project", project); shell.evaluate("project." + method); }
From source file:com.linkedin.sample.Main.java
public static void main(String[] args) { /*// ww w . j a v a 2 s . c o m we need a OAuthService to handle authentication and the subsequent calls. Since we are going to use the REST APIs we need to generate a request token as the first step in the call. Once we get an access toke we can continue to use that until the API key changes or auth is revoked. Therefore, to make this sample easier to re-use we serialize the AuthHandler (which stores the access token) to disk and then reuse it. When you first run this code please insure that you fill in the API_KEY and API_SECRET above with your own credentials and if there is a service.dat file in the code please delete it. */ //The Access Token is used in all Data calls to the APIs - it basically says our application has been given access //to the approved information in LinkedIn Token accessToken = null; //Using the Scribe library we enter the information needed to begin the chain of Oauth2 calls. OAuthService service = new ServiceBuilder().provider(LinkedInApi.class).apiKey(API_KEY) .apiSecret(API_SECRET).build(); /************************************* * This first piece of code handles all the pieces needed to be granted access to make a data call */ try { File file = new File("service.dat"); if (file.exists()) { //if the file exists we assume it has the AuthHandler in it - which in turn contains the Access Token ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file)); AuthHandler authHandler = (AuthHandler) inputStream.readObject(); accessToken = authHandler.getAccessToken(); } else { System.out.println("There is no stored Access token we need to make one"); //In the constructor the AuthHandler goes through the chain of calls to create an Access Token AuthHandler authHandler = new AuthHandler(service); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("service.dat")); outputStream.writeObject(authHandler); outputStream.close(); accessToken = authHandler.getAccessToken(); } } catch (Exception e) { System.out.println("Threw an exception when serializing: " + e.getClass() + " :: " + e.getMessage()); } /* * We are all done getting access - time to get busy getting data *************************************/ /************************** * * Querying the LinkedIn API * **************************/ System.out.println(); System.out.println("********A basic user profile call********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/profile-api String url = "http://api.linkedin.com/v1/people/~"; OAuthRequest request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); Response response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get the profile in JSON********"); //This basic call profile in JSON format //You can read more about JSON here http://json.org url = "http://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); request.addHeader("x-li-format", "json"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get the profile in JSON using query parameter********"); //This basic call profile in JSON format. Please note the call above is the preferred method. //You can read more about JSON here http://json.org url = "http://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("format", "json"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get my connections - going into a resource********"); //This basic call gets all your connections each one will be in a person tag with some profile information //https://developer.linkedin.com/documents/connections-api url = "http://api.linkedin.com/v1/people/~/connections"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get only 10 connections - using parameters********"); //This basic call gets only 10 connections - each one will be in a person tag with some profile information //https://developer.linkedin.com/documents/connections-api //more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string url = "http://api.linkedin.com/v1/people/~/connections"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("count", "10"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********GET network updates that are CONN and SHAR********"); //This basic call get connection updates from your connections //https://developer.linkedin.com/documents/get-network-updates-and-statistics-api //specifics on updates https://developer.linkedin.com/documents/network-update-types url = "http://api.linkedin.com/v1/people/~/network/updates"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("type", "SHAR"); request.addQuerystringParameter("type", "CONN"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********"); //This basic call get connection updates from your connections //https://developer.linkedin.com/documents/people-search-api#Facets //Why doesn't this look like //people-search?title=developer&location=fr&industry=4 //url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0"; url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("title", "Dveloppeur"); request.addQuerystringParameter("facet", "industry,4"); request.addQuerystringParameter("facets", "location,industry"); System.out.println(request.getUrl()); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); /////////////////field selectors System.out.println("********A basic user profile call with field selectors********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/field-selectors url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out .println("********A basic user profile call with field selectors going into a subresource********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/field-selectors url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********A basic user profile call into a subresource return data in JSON********"); //The ~ means yourself - so this should return the basic default information for your profile //https://developer.linkedin.com/documents/field-selectors url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********A more complicated example using postings into groups********"); //https://developer.linkedin.com/documents/field-selectors //https://developer.linkedin.com/documents/groups-api url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); /************************** * * Wrting to the LinkedIn API * **************************/ /* * Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out * some code. Uncomment if you'd like to see writes in action. * * System.out.println("********Write to the share - using XML********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); request.addHeader("Content-Type", "text/xml"); //Make an XML document Document doc = DocumentHelper.createDocument(); Element share = doc.addElement("share"); share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs"); Element content = share.addElement("content"); content.addElement("title").addText("A title for your share"); content.addElement("submitted-url").addText("http://developer.linkedin.com"); share.addElement("visibility").addElement("code").addText("anyone"); request.addPayload(doc.asXML()); service.signRequest(accessToken, request); response = request.send(); //there is no body just a header System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); System.out.println("********Write to the share and to Twitter - using XML********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); request.addQuerystringParameter("twitter-post","true"); request.addHeader("Content-Type", "text/xml"); //Make an XML document doc = DocumentHelper.createDocument(); share = doc.addElement("share"); share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter"); content = share.addElement("content"); content.addElement("title").addText("A title for your share"); content.addElement("submitted-url").addText("http://developer.linkedin.com"); share.addElement("visibility").addElement("code").addText("anyone"); request.addPayload(doc.asXML()); service.signRequest(accessToken, request); response = request.send(); //there is no body just a header System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); System.out.println("********Write to the share and to twitter - using JSON ********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api //NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); //set the headers to the server knows what we are sending request.addHeader("Content-Type", "application/json"); request.addHeader("x-li-format", "json"); //make the json payload using json-simple Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put("comment", "Posting from the API using JSON"); JSONObject contentObject = new JSONObject(); contentObject.put("title", "This is a another test post"); contentObject.put("submitted-url","http://www.linkedin.com"); contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg"); jsonMap.put("content", contentObject); JSONObject visibilityObject = new JSONObject(); visibilityObject.put("code", "anyone"); jsonMap.put("visibility", visibilityObject); request.addPayload(JSONValue.toJSONString(jsonMap)); service.signRequest(accessToken, request); response = request.send(); //again no body - just headers System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); */ /************************** * * Understanding the response, creating logging, request and response headers * **************************/ System.out.println(); System.out.println("********A basic user profile call and response dissected********"); //This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle //https://developer.linkedin.com/documents/debugging-api-calls url = "https://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); //get all the headers System.out.println("Request headers: " + request.getHeaders().toString()); System.out.println("Response headers: " + response.getHeaders().toString()); //url requested System.out.println("Original location is: " + request.getHeaders().get("content-location")); //Date of response System.out.println("The datetime of the response is: " + response.getHeader("Date")); //the format of the response System.out.println("Format is: " + response.getHeader("x-li-format")); //Content-type of the response System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n"); //get the HTTP response code - such as 200 or 404 int responseNumber = response.getCode(); if (responseNumber >= 199 && responseNumber < 300) { System.out.println("HOORAY IT WORKED!!"); System.out.println(response.getBody()); } else if (responseNumber >= 500 && responseNumber < 600) { //you could actually raise an exception here in your own code System.out.println("Ruh Roh application error of type 500: " + responseNumber); System.out.println(response.getBody()); } else if (responseNumber == 403) { System.out.println("A 403 was returned which usually means you have reached a throttle limit"); } else if (responseNumber == 401) { System.out.println("A 401 was returned which is a Oauth signature error"); System.out.println(response.getBody()); } else if (responseNumber == 405) { System.out.println( "A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc)."); } else { System.out.println("We got a different response that we should add to the list: " + responseNumber + " and report it in the forums"); System.out.println(response.getBody()); } System.out.println(); System.out.println(); System.out.println("********A basic error logging function********"); // Now demonstrate how to make a logging function which provides us the info we need to // properly help debug issues. Please use the logged block from here when requesting // help in the forums. url = "https://api.linkedin.com/v1/people/FOOBARBAZ"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); responseNumber = response.getCode(); if (responseNumber < 200 || responseNumber >= 300) { logDiagnostics(request, response); } else { System.out.println("You were supposed to submit a bad request"); } System.out.println("******Finished******"); }
From source file:InstallJars.java
/** * Main command line entry point./* w w w . j a v a2s. c o m*/ * * @param args */ public static void main(final String[] args) { if (args.length == 0) { printHelp(); System.exit(0); } String propName = null; boolean expand = true; boolean verbose = true; boolean run = true; String params = "cmd /c java"; // process arguments for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.charAt(0) == '-') { // switch arg = arg.substring(1); if (arg.equalsIgnoreCase("quiet")) { verbose = false; } else if (arg.equalsIgnoreCase("verbose")) { verbose = true; } else if (arg.equalsIgnoreCase("expand")) { expand = true; } else if (arg.equalsIgnoreCase("noexpand")) { expand = false; } else if (arg.equalsIgnoreCase("run")) { run = true; } else if (arg.equalsIgnoreCase("norun")) { run = false; } else if (arg.equalsIgnoreCase("java")) { run = false; if (i < args.length - 1) { params = args[++i]; } } else { System.err.println("Invalid switch - " + arg); System.exit(1); } } else { if (propName == null) { propName = arg; } else { System.err.println("Too many parameters - " + arg); System.exit(1); } } } if (propName == null) { propName = "InstallJars.properties"; } // do the install try { InstallJars ij = new InstallJars(expand, verbose, run, propName, params); ij.printUsage(); String cp = ij.install(); System.out.println("\nRecomended additions to your classpath - " + cp); } catch (Exception e) { System.err.println("\n" + e.getClass().getName() + ": " + e.getMessage()); if (verbose) { e.printStackTrace(); // *** debug *** } System.exit(2); } }