List of usage examples for java.lang System currentTimeMillis
@HotSpotIntrinsicCandidate public static native long currentTimeMillis();
From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java
public static void main(String[] args) throws Exception { if (args.length != 4 && args.length != 5) { System.err.println(//from w w w . ja v a 2s .com "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional)."); return; } File queryDir = new File(args[0]); String resourceUrl = args[1]; int warmUpRounds = Integer.parseInt(args[2]); int testRounds = Integer.parseInt(args[3]); File resultDir; if (args.length == 4) { resultDir = null; } else { resultDir = new File(args[4]); if (!resultDir.exists()) { if (!resultDir.mkdirs()) { throw new RuntimeException("Failed to create result directory: " + resultDir); } } } File[] queryFiles = queryDir.listFiles(); assert queryFiles != null; Arrays.sort(queryFiles); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(resourceUrl); httpPost.addHeader("content-type", "application/json"); for (File queryFile : queryFiles) { StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) { int length; while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) { stringBuilder.append(new String(CHAR_BUFFER, 0, length)); } } String query = stringBuilder.toString(); httpPost.setEntity(new StringEntity(query)); System.out.println( "--------------------------------------------------------------------------------"); System.out.println("Running query: " + query); System.out.println( "--------------------------------------------------------------------------------"); // Warm-up Rounds System.out.println("Run " + warmUpRounds + " times to warm up..."); for (int i = 0; i < warmUpRounds; i++) { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); System.out.print('*'); } System.out.println(); // Test Rounds System.out.println("Run " + testRounds + " times to get response time statistics..."); long[] responseTimes = new long[testRounds]; long totalResponseTime = 0L; for (int i = 0; i < testRounds; i++) { long startTime = System.currentTimeMillis(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); long responseTime = System.currentTimeMillis() - startTime; responseTimes[i] = responseTime; totalResponseTime += responseTime; System.out.print(responseTime + "ms "); } System.out.println(); // Store result. if (resultDir != null) { File resultFile = new File(resultDir, queryFile.getName() + ".result"); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try (BufferedInputStream bufferedInputStream = new BufferedInputStream( httpResponse.getEntity().getContent()); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) { int length; while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) { bufferedWriter.write(new String(BYTE_BUFFER, 0, length)); } } httpResponse.close(); } // Process response times. double averageResponseTime = (double) totalResponseTime / testRounds; double temp = 0; for (long responseTime : responseTimes) { temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime); } double standardDeviation = Math.sqrt(temp / testRounds); System.out.println("Average response time: " + averageResponseTime + "ms"); System.out.println("Standard deviation: " + standardDeviation); } } }
From source file:dfki.sb.rabbitmqjava.RabbitMQObjectStreamClient.java
public static void main(String[] argv) { int numMessages = 10000; RabbitMQObjectStreamClient rpcClient = null; String response = null;// w ww . ja v a 2 s.com try { rpcClient = new RabbitMQObjectStreamClient(); sendMessages(20000, rpcClient); long startTime = System.currentTimeMillis(); sendMessages(numMessages, rpcClient); long finishTime = System.currentTimeMillis(); long difference = finishTime - startTime; difference = difference * 1000; double latency = (double) difference / (numMessages * 2.0); rpcClient.sendDesiconnectSignal(); System.out.println(String.format("\n\nAverage latency in microseconds %.3f\n\n\n", latency)); System.out.println("Finished"); } catch (Exception e) { e.printStackTrace(); } finally { if (rpcClient != null) { try { rpcClient.close(); } catch (Exception ignore) { } } } }
From source file:com.utdallas.s3lab.smvhunter.monkey.MonkeyMe.java
/** * @param args//www . j ava 2s . co m */ public static void main(String[] args) throws Exception { logger.info("start time ==== " + System.currentTimeMillis()); try { //load the adb location from the props file Properties props = new Properties(); props.load(new FileInputStream(new File("adb.props"))); //set the adb location WindowUpdate.adbLocation = props.getProperty("adb_location"); adbLocation = props.getProperty("adb_location"); //set root dir ROOT_DIRECTORY = props.getProperty("root_dir"); //completed txt completedFile = new File(ROOT_DIRECTORY + "tested.txt"); //db location for static analysis dbLocation = props.getProperty("db_location"); //location for smart input generation output smartInputLocation = props.getProperty("smart_input_location"); //udp dump location udpDumpLocation = props.getProperty("udp_dump_location"); //logcat dump location logCatLocation = props.getProperty("log_cat_location"); //strace output location straceOutputLocation = props.getProperty("strace_output_location"); //strace dump location straceDumpLocation = props.getProperty("strace_output_location"); //set x and y coords UIEnumerator.screenX = props.getProperty("x"); UIEnumerator.screenY = props.getProperty("y"); DeviceOfflineMonitor.START_EMULATOR = props.getProperty("restart"); //read output of static analysis readFromStaticAnalysisText(); logger.info("Read static analysis output"); readFromSmartInputText(); logger.info("Read smart input generation output"); //populate the queue with apps which are only present in the static analysis @SuppressWarnings("unchecked") final Set<? extends String> sslApps = new HashSet<String>( CollectionUtils.collect(FileUtils.readLines(new File(dbLocation)), new Transformer() { @Override public Object transform(Object input) { //get app file name String temp = StringUtils.substringBefore(input.toString(), " "); return StringUtils.substringAfterLast(temp, "/"); } })); Collection<File> fileList = FileUtils.listFiles(new File(ROOT_DIRECTORY), new String[] { "apk" }, false); CollectionUtils.filter(fileList, new Predicate() { @Override public boolean evaluate(Object object) { return sslApps.contains(StringUtils.substringAfterLast(object.toString(), "/")); } }); apkQueue = new LinkedBlockingDeque<File>(fileList); logger.info("finished listing files from the root directory"); try { //populate the tested apk list completedApps.addAll(FileUtils.readLines(completedFile)); } catch (Exception e) { //pass except logger.info("No tested.txt file found"); //create new file if (completedFile.createNewFile()) { logger.info("tested.txt created in root directory"); } else { logger.info("tested.txt file could not be created"); } } //get the executors for managing the emulators executors = Executors.newCachedThreadPool(); //set the devicemonitor exec DeviceOfflineMonitor.exec = executors; final List<Future<?>> futureList = new ArrayList<Future<?>>(); //start the offline device monitor (emulator management thread) logger.info("Starting Device Offline Monitor Thread"); executors.submit(new DeviceOfflineMonitor()); //get ADB backend object for device change listener AdbBackend adb = new AdbBackend(); //register for device change and wait for events //once event is received, start the MonkeyMe thread MonkeyDeviceChangeListener deviceChangeListener = new MonkeyDeviceChangeListener(executors, futureList); AndroidDebugBridge.addDeviceChangeListener(deviceChangeListener); logger.info("Listening to changes in devices (emulators)"); //wait for the latch to come down //this means that all the apks have been processed cdl.await(); logger.info("Finished testing all apps waiting for threads to join"); //now wait for every thread to finish for (Future<?> future : futureList) { future.get(); } logger.info("All threads terminated"); //stop listening for device update AndroidDebugBridge.removeDeviceChangeListener(deviceChangeListener); //stop the debug bridge AndroidDebugBridge.terminate(); //stop offline device monitor DeviceOfflineMonitor.stop = true; logger.info("adb and listeners terminated"); } finally { logger.info("Executing this finally"); executors.shutdownNow(); } logger.info("THE END!!"); }
From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaTraverser.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input Kyanos resource directory"); inputOpt.setArgs(1);//from w ww . ja va 2s . c om inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); options.addOption(inputOpt); options.addOption(inClassOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); URI uri = URI.createURI("morsa://" + commandLine.getOptionValue(IN)); Class<?> inClazz = MorsaTraverser.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa", new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory())); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); loadOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost"); loadOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000); loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false); // loadOpts.put(IMorsaResource.OPTION_CACHE_POLICY, FIFOEObjectCachePolicy.class.getName()); // loadOpts.put(IMorsaResource.OPTION_MAX_CACHE_SIZE, 30000); // loadOpts.put(IMorsaResource.OPTION_CACHE_FLUSH_FACTOR, 0.3f); // loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD_STRATEGY, IMorsaResource.OPTION_SINGLE_LOAD_STRATEGY); // loadOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, true); resource.load(loadOpts); LOG.log(Level.INFO, "Start counting"); int count = 0; long begin = System.currentTimeMillis(); for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator .next(), count++) ; long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End counting"); LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count)); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:org.ala.hbase.RepoDataLoader.java
/** * This takes a list of infosource ids... * <p/>/*from www . j a v a 2s . co m*/ * Usage: -stats or -reindex or -gList and list of infosourceId * * @param args */ public static void main(String[] args) throws Exception { //RepoDataLoader loader = new RepoDataLoader(); ApplicationContext context = SpringUtils.getContext(); RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class); long start = System.currentTimeMillis(); loader.loadInfoSources(); String filePath = repositoryDir; if (args.length > 0) { if (args[0].equalsIgnoreCase("-stats")) { loader.statsOnly = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); } if (args[0].equalsIgnoreCase("-reindex")) { loader.reindex = true; loader.indexer = context.getBean(PartialIndex.class); args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -reindex: " + loader.reindex); logger.debug("reindex url: " + loader.reindexUrl); } if (args[0].equalsIgnoreCase("-gList")) { loader.gList = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -gList: " + loader.gList); } if (args[0].equalsIgnoreCase("-biocache")) { Hashtable<String, String> hashTable = new Hashtable<String, String>(); hashTable.put("accept", "application/json"); ObjectMapper mapper = new ObjectMapper(); mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); RestfulClient restfulClient = new RestfulClient(0); String fq = "&fq="; if (args.length > 1) { java.util.Date date = new java.util.Date(); if (args[1].equals("-lastWeek")) { date = DateUtils.addWeeks(date, -1); } else if (args[1].equals("-lastMonth")) { date = DateUtils.addMonths(date, -1); } else if (args[1].equals("-lastYear")) { date = DateUtils.addYears(date, -1); } else date = null; if (date != null) { SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D"; } } Object[] resp = restfulClient .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0", hashTable); logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0"); if ((Integer) resp[0] == HttpStatus.SC_OK) { String content = resp[1].toString(); logger.debug(resp[1]); if (content != null && content.length() > "[]".length()) { Map map = mapper.readValue(content, Map.class); try { List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map .get("facetResults")).get(0)).get("fieldResult")); Set<String> arg = new LinkedHashSet<String>(); for (int i = 0; i < list.size(); i++) { java.util.LinkedHashMap<String, String> value = list.get(i); String dataResource = getDataResource(value.get("fq")); Object provider = (loader.getUidInfoSourceMap().get(dataResource)); if (provider != null) { arg.add(provider.toString()); } } logger.info("Set of biocache infosource ids to load: " + arg); args = new String[] {}; args = arg.toArray(args); //handle the situation where biocache-service reports no data resources if (args.length < 1) { logger.error("No biocache data resources found. Unable to load."); System.exit(0); } } catch (Exception e) { logger.error("ERROR: exit process....." + e); e.printStackTrace(); System.exit(0); } } } else { logger.warn("Unable to process url: "); } } } int filesRead = loader.load(filePath, args); //FIX ME - move to config long finish = System.currentTimeMillis(); logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes " + ((finish - start) / 1000) + " seconds."); System.exit(1); }
From source file:com.linkedin.pinot.perf.FilterOperatorBenchmark.java
public static void main(String[] args) throws Exception { String rootDir = args[0];//from w w w.ja va 2 s . co m File[] segmentDirs = new File(rootDir).listFiles(); String query = args[1]; AtomicInteger totalDocsMatched = new AtomicInteger(0); Pql2Compiler pql2Compiler = new Pql2Compiler(); BrokerRequest brokerRequest = pql2Compiler.compileToBrokerRequest(query); List<Callable<Void>> segmentProcessors = new ArrayList<>(); long[] timesSpent = new long[segmentDirs.length]; for (int i = 0; i < segmentDirs.length; i++) { File indexSegmentDir = segmentDirs[i]; System.out.println("Loading " + indexSegmentDir.getName()); Configuration tableDataManagerConfig = new PropertiesConfiguration(); List<String> invertedColumns = new ArrayList<>(); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".bitmap.inv"); } }; String[] indexFiles = indexSegmentDir.list(filter); for (String indexFileName : indexFiles) { invertedColumns.add(indexFileName.replace(".bitmap.inv", "")); } tableDataManagerConfig.setProperty(IndexLoadingConfigMetadata.KEY_OF_LOADING_INVERTED_INDEX, invertedColumns); IndexLoadingConfigMetadata indexLoadingConfigMetadata = new IndexLoadingConfigMetadata( tableDataManagerConfig); IndexSegmentImpl indexSegmentImpl = (IndexSegmentImpl) Loaders.IndexSegment.load(indexSegmentDir, ReadMode.heap, indexLoadingConfigMetadata); segmentProcessors .add(new SegmentProcessor(i, indexSegmentImpl, brokerRequest, totalDocsMatched, timesSpent)); } ExecutorService executorService = Executors.newCachedThreadPool(); for (int run = 0; run < 5; run++) { System.out.println("START RUN:" + run); totalDocsMatched.set(0); long start = System.currentTimeMillis(); List<Future<Void>> futures = executorService.invokeAll(segmentProcessors); for (int i = 0; i < futures.size(); i++) { futures.get(i).get(); } long end = System.currentTimeMillis(); System.out.println("Total docs matched:" + totalDocsMatched + " took:" + (end - start)); System.out.println("Times spent:" + Arrays.toString(timesSpent)); System.out.println("END RUN:" + run); } System.exit(0); }
From source file:com.ingby.socbox.bischeck.test.JDBCtest.java
static public void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { CommandLineParser parser = new GnuParser(); CommandLine line = null;/*w ww. ja va 2 s .co m*/ // create the Options Options options = new Options(); options.addOption("u", "usage", false, "show usage."); options.addOption("c", "connection", true, "the connection url"); options.addOption("s", "sql", true, "the sql statement to run"); options.addOption("m", "meta", true, "get the table meta data"); options.addOption("C", "columns", true, "the number of columns to display, default 1"); options.addOption("d", "driver", true, "the driver class"); options.addOption("v", "verbose", false, "verbose outbout"); try { // parse the command line arguments line = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { System.out.println("Command parse error:" + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JDBCtest", options); Util.ShellExit(1); } if (line.hasOption("verbose")) { verbose = true; } if (line.hasOption("usage")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bischeck", options); Util.ShellExit(0); } String driverclassname = null; if (!line.hasOption("driver")) { System.out.println("Driver class must be set"); Util.ShellExit(1); } else { driverclassname = line.getOptionValue("driver"); outputln("DriverClass: " + driverclassname); } String connectionname = null; if (!line.hasOption("connection")) { System.out.println("Connection url must be set"); Util.ShellExit(1); } else { connectionname = line.getOptionValue("connection"); outputln("Connection: " + connectionname); } String sql = null; String tablename = null; if (line.hasOption("sql")) { sql = line.getOptionValue("sql"); outputln("SQL: " + sql); } if (line.hasOption("meta")) { tablename = line.getOptionValue("meta"); outputln("Table: " + tablename); } int nrColumns = 1; if (line.hasOption("columns")) { nrColumns = new Integer(line.getOptionValue("columns")); } long execStart = 0l; long execEnd = 0l; long openStart = 0l; long openEnd = 0l; long metaStart = 0l; long metaEnd = 0l; Class.forName(driverclassname).newInstance(); openStart = System.currentTimeMillis(); Connection conn = DriverManager.getConnection(connectionname); openEnd = System.currentTimeMillis(); if (tablename != null) { ResultSet rsCol = null; metaStart = System.currentTimeMillis(); DatabaseMetaData md = conn.getMetaData(); metaEnd = System.currentTimeMillis(); rsCol = md.getColumns(null, null, tablename, null); if (verbose) { tabular("COLUMN_NAME"); tabular("TYPE_NAME"); tabular("COLUMN_SIZE"); tabularlast("DATA_TYPE"); outputln(""); } while (rsCol.next()) { tabular(rsCol.getString("COLUMN_NAME")); tabular(rsCol.getString("TYPE_NAME")); tabular(rsCol.getString("COLUMN_SIZE")); tabularlast(rsCol.getString("DATA_TYPE")); outputln("", true); } } if (sql != null) { Statement stat = conn.createStatement(); stat.setQueryTimeout(10); execStart = System.currentTimeMillis(); ResultSet res = stat.executeQuery(sql); ResultSetMetaData rsmd = res.getMetaData(); execEnd = System.currentTimeMillis(); if (verbose) { for (int i = 1; i < nrColumns + 1; i++) { if (i != nrColumns) tabular(rsmd.getColumnName(i)); else tabularlast(rsmd.getColumnName(i)); } outputln(""); } while (res.next()) { for (int i = 1; i < nrColumns + 1; i++) { if (i != nrColumns) tabular(res.getString(i)); else tabularlast(res.getString(i)); } outputln("", true); } stat.close(); res.close(); } conn.close(); // Print the execution times outputln("Open time: " + (openEnd - openStart) + " ms"); if (line.hasOption("meta")) { outputln("Meta time: " + (metaEnd - metaStart) + " ms"); } if (line.hasOption("sql")) { outputln("Exec time: " + (execEnd - execStart) + " ms"); } }
From source file:playground.jbischoff.carsharing.data.VBBRouteCatcher.java
public static void main(String[] args) throws IOException, Exception { // Hansaplatz-Friedrich-Wilhelm-Platz // Coord c = new CoordImpl(52.519580833333,13.359681944444); // Coord d = new CoordImpl(52.470137777778,13.335396944444); //Salzufer-Hoenow Coord c = new CoordImpl(52.5188, 13.32183); Coord d = new CoordImpl(52.5307913, 13.6303349); VBBRouteCatcher rc = new VBBRouteCatcher(c, d, System.currentTimeMillis(), "vbbTest.xml.gz"); }
From source file:examples.StatePersistence.java
public static void main(String[] args) throws Exception { // Connect to localhost and use the travel-sample bucket final Client client = Client.configure().hostnames("localhost").bucket(BUCKET).build(); // Don't do anything with control events in this example client.controlEventHandler(new ControlEventHandler() { @Override/*from w w w . j a v a 2 s.c o m*/ public void onEvent(ChannelFlowController flowController, ByteBuf event) { if (DcpSnapshotMarkerRequest.is(event)) { flowController.ack(event); } event.release(); } }); // Print out Mutations and Deletions client.dataEventHandler(new DataEventHandler() { @Override public void onEvent(ChannelFlowController flowController, ByteBuf event) { if (DcpMutationMessage.is(event)) { System.out.println("Mutation: " + DcpMutationMessage.toString(event)); // You can print the content via DcpMutationMessage.content(event).toString(CharsetUtil.UTF_8); } else if (DcpDeletionMessage.is(event)) { System.out.println("Deletion: " + DcpDeletionMessage.toString(event)); } event.release(); } }); // Connect the sockets client.connect().await(); // Try to load the persisted state from file if it exists File file = new File(FILENAME); byte[] persisted = null; if (file.exists()) { FileInputStream fis = new FileInputStream(FILENAME); persisted = IOUtils.toByteArray(fis); fis.close(); } // if the persisted file exists recover, if not start from beginning client.recoverOrInitializeState(StateFormat.JSON, persisted, StreamFrom.BEGINNING, StreamTo.INFINITY) .await(); // Start streaming on all partitions client.startStreaming().await(); // Persist the State ever 10 seconds while (true) { Thread.sleep(TimeUnit.SECONDS.toMillis(10)); // export the state as a JSON byte array byte[] state = client.sessionState().export(StateFormat.JSON); // Write it to a file FileOutputStream output = new FileOutputStream(new File(FILENAME)); IOUtils.write(state, output); output.close(); System.out.println(System.currentTimeMillis() + " - Persisted State!"); } }
From source file:com.amazonaws.services.iot.client.sample.shadowEcho.ShadowEchoSample.java
public static void main(String args[]) throws IOException, AWSIotException, AWSIotTimeoutException, InterruptedException { CommandArguments arguments = CommandArguments.parse(args); initClient(arguments);/*from ww w . ja v a 2 s . c o m*/ String thingName = arguments.getNotNull("thingName", SampleUtil.getConfig("thingName")); AWSIotDevice device = new AWSIotDevice(thingName); awsIotClient.attach(device); awsIotClient.connect(); // Delete existing document if any device.delete(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Thing thing = new Thing(); while (true) { long desired = thing.state.desired.counter; thing.state.reported.counter = desired; thing.state.desired.counter = desired + 1; String jsonState = objectMapper.writeValueAsString(thing); try { // Send updated document to the shadow device.update(jsonState); System.out.println(System.currentTimeMillis() + ": >>> " + jsonState); } catch (AWSIotException e) { System.out.println(System.currentTimeMillis() + ": update failed for " + jsonState); continue; } try { // Retrieve updated document from the shadow String shadowState = device.get(); System.out.println(System.currentTimeMillis() + ": <<< " + shadowState); thing = objectMapper.readValue(shadowState, Thing.class); } catch (AWSIotException e) { System.out.println(System.currentTimeMillis() + ": get failed for " + jsonState); continue; } Thread.sleep(1000); } }