List of usage examples for java.lang StringBuilder StringBuilder
@HotSpotIntrinsicCandidate
public StringBuilder()
From source file:icevaluation.BingAPIAccess.java
public static void main(String[] args) { String searchText = "arts site:wikipedia.org"; searchText = searchText.replaceAll(" ", "%20"); // String accountKey="jTRIJt9d8DR2QT/Z3BJCAvY1BfoXj0zRYgSZ8deqHHo"; String accountKey = "JfeJSA3x6CtsyVai0+KEP0A6CYEUBT8VWhZmm9CS738"; byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes()); String accountKeyEnc = new String(accountKeyBytes); URL url;//from w ww . j a v a 2 s . c om try { url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27" + searchText + "%27&$format=JSON"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder sb = new StringBuilder(); String output; System.out.println("Output from Server .... \n"); //write json to string sb int c = 0; if ((output = br.readLine()) != null) { System.out.println("Output is: " + output); sb.append(output); c++; //System.out.println("C:"+c); } conn.disconnect(); //find webtotal among output int find = sb.indexOf("\"WebTotal\":\""); int startindex = find + 12; System.out.println("Find: " + find); int lastindex = sb.indexOf("\",\"WebOffset\""); System.out.println(sb.substring(startindex, lastindex)); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.liferay.mobile.sdk.BuilderAntTask.java
public static void main(String[] args) { Map<String, String> arguments = parseArguments(args); String url = arguments.get("url"); String context = arguments.get("context"); String filter = arguments.get("filter"); StringBuilder sb = new StringBuilder(); sb.append(url);//from ww w . ja va2 s .co m if (Validator.isNotNull(context)) { sb.append("/"); sb.append(context); } sb.append("/api/jsonws?discover"); if (Validator.isNull(filter)) { sb.append("=/*"); } else { sb.append("=/"); sb.append(filter); sb.append("/*"); } HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(sb.toString()); DiscoveryResponseHandler handler = new DiscoveryResponseHandler(); try { String builderType = arguments.get("builder"); Builder builder = null; if (builderType.equals("android")) { builder = new AndroidBuilder(); } Discovery discovery = client.execute(get, handler); PortalVersion version = HttpUtil.getPortalVersion(url); if (Validator.isNull(filter)) { builder.buildAll(version, discovery); } else { builder.build(filter, version, discovery); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.javacreed.examples.spring.CreateBigTable.java
public static void main(final String[] args) throws Exception { final ComboPooledDataSource ds = DbUtils.createDs(); try {//w ww . ja v a2s.com final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds); CreateBigTable.LOGGER.debug("Dropping table (if exists)"); jdbcTemplate.update("DROP TABLE IF EXISTS `big_table`"); CreateBigTable.LOGGER.debug("Creating table"); jdbcTemplate.update("CREATE TABLE `big_table`(`id` INT(20), `name` VARCHAR(128))"); CreateBigTable.LOGGER.debug("Adding records"); final StringBuilder query = new StringBuilder(); for (int i = 0, b = 1; i < 1000000; i++) { if (i % 500 == 0) { if (i > 0) { CreateBigTable.LOGGER.debug("Adding records (batch {})", b++); jdbcTemplate.update(query.toString()); query.setLength(0); } query.append("INSERT INTO `big_table` (`id`, `name`) VALUES "); } else { query.append(","); } query.append(" (" + (i + 1) + ", 'Pack my box with five dozen liquor jugs.')"); } CreateBigTable.LOGGER.debug("Adding last batch"); jdbcTemplate.update(query.toString()); } finally { DbUtils.closeQuietly(ds); } CreateBigTable.LOGGER.debug("Done"); }
From source file:HelloSmartsheet.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try {/*from w w w .j ava2 s. c o m*/ System.out.println("STARTING HelloSmartsheet..."); //Create a BufferedReader to read user input. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Smartsheet API access token:"); String accessToken = in.readLine(); System.out.println("Fetching list of your sheets..."); //Create a connection and fetch the list of sheets connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; //Read the response line by line. while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); //Use Jackson to conver the JSON string to a List of Sheets List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() { }); if (sheets.size() == 0) { System.out.println("You don't have any sheets. Goodbye!"); return; } System.out.println("Total sheets: " + sheets.size()); int i = 1; for (Sheet sheet : sheets) { System.out.println(i++ + ": " + sheet.name); } System.out.print("Enter the number of the sheet you want to share: "); //Prompt the user to provide the sheet number, the email address, and the access level Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected. Sheet chosenSheet = sheets.get(sheetNumber - 1); System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: "); String email = in.readLine(); System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": "); String accessLevel = in.readLine(); //Create a share object Share share = new Share(); share.setEmail(email); share.setAccessLevel(accessLevel); System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + "."); //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's') connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId())) .openConnection(); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); //Serialize the Share object writer.write(mapper.writeValueAsString(share)); writer.close(); //Read the response and parse the JSON reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } Result result = mapper.readValue(response.toString(), Result.class); System.out.println("Sheet shared successfully, share ID " + result.result.id); System.out.println("Press any key to quit."); in.read(); } catch (IOException e) { BufferedReader reader = new BufferedReader( new InputStreamReader(((HttpURLConnection) connection).getErrorStream())); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result result = mapper.readValue(response.toString(), Result.class); System.out.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:AdminExample.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account. String user1Email = ""; //You need access to these two email account. String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. //joe@gmail.com will get email sent to joe+user1@gmail.com try {// w ww. j a v a 2 s. c om BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Adding user " + user1Email); //Add the users: User user = new User(); user.setEmail(user1Email); user.setAdmin(false); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser1Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId()); user = new User(); user.setEmail(user2Email); user.setAdmin(true); user.setLicensedSheetCreator(true); connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), user); Result<User> newUser2Result = mapper.readValue(connection.getInputStream(), new TypeReference<Result<User>>() { }); System.out.println( "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId()); System.out.println("Please visit the email inbox for the users " + user1Email + " and " + user2Email + " and confirm membership to the account."); System.out.print("Press Enter to continue"); in.readLine(); //List all the users of the org connection = (HttpURLConnection) new URL(USERS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() { }); System.out.println("The following are members of your account: "); for (User orgUser : users) { System.out.println("\t" + orgUser.getEmail()); } //Create a sheet as the admin Sheet newSheet = new Sheet(); newSheet.setName("Admin's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user1 newSheet = new Sheet(); newSheet.setName("User 1's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); //Here is where the magic happens - Any action performed in this call will be on behalf of the //user provided. Note that this person must be a confirmed member of your org. //Also note that the email address is url-encoded. connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //Create a sheet as user2 newSheet = new Sheet(); newSheet.setName("User 2's Sheet"); newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null), new Column("Column 2", "TEXT_NUMBER", null, null, null), new Column("Column 3", "TEXT_NUMBER", null, null, null))); connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); //List all the sheets in the org: System.out.println("The following sheets are owned by members of your account: "); connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() { }); for (Sheet orgSheet : allSheets) { System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner()); } //Now delete user1 and transfer their sheets to user2 connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "") + "?transferTo=" + newUser2Result.getResult().getId()).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8")); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("DELETE"); Result<Object> resultObject = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Object>>() { }); System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred()); } catch (IOException e) { InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream(); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result<?> result = mapper.readValue(response.toString(), Result.class); System.err.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.mycompany.test.Jaroop.java
/** * This is the main program which will receive the request, calls required methods * and processes the response./*from www . j a va2 s.c o m*/ * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner scannedInput = new Scanner(System.in); String in = ""; if (args.length == 0) { System.out.println("Enter the query"); in = scannedInput.nextLine(); } else { in = args[0]; } in = in.toLowerCase().replaceAll("\\s+", "_"); int httpStatus = checkInvalidInput(in); if (httpStatus == 0) { System.out.print("Not found"); System.exit(0); } String url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + in; HttpURLConnection connection = getConnection(url); BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String request = ""; StringBuilder response = new StringBuilder(); while ((request = input.readLine()) != null) { //only appending what ever is required for JSON parsing and ignoring the rest response.append("{"); //appending the key "extract" to the string so that the JSON parser can parse it's value, //also we don't need last 3 paranthesis in the response, excluding them as well. response.append(request.substring(request.indexOf("\"extract"), request.length() - 3)); } parseJSON(response.toString()); }
From source file:org.kuali.kfs.rest.AccountingPeriodCloseJob.java
public static void main(String[] args) { try {// w ww .j a v a 2s . c om DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost("http://localhost:8080/kfs-dev/coa/accounting_periods/close"); request.addHeader("accept", "application/json"); request.addHeader("content-type", "application/json"); request.addHeader("authorization", "NSA_this_is_for_you"); StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("\"description\":\"Document: The Next Generation\","); sb.append("\"universityFiscalYear\": 2016,"); sb.append("\"universityFiscalPeriodCode\": \"03\""); sb.append("}"); StringEntity data = new StringEntity(sb.toString()); request.setEntity(data); HttpResponse response = httpClient.execute(request); System.out.println("Status Code: " + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } httpClient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:HrefMatch.java
public static void main(String[] args) { try {/*from www. j a v a2 s. co m*/ // get URL string from command line or use default String urlString; if (args.length > 0) urlString = args[0]; else urlString = "http://java.sun.com"; // open reader for URL InputStreamReader in = new InputStreamReader(new URL(urlString).openStream()); // read contents into string builder StringBuilder input = new StringBuilder(); int ch; while ((ch = in.read()) != -1) input.append((char) ch); // search for all occurrences of pattern String patternString = "<a\\s+href\\s*=\\s*(\"[^\"]*\"|[^\\s>]*)\\s*>"; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(input); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String match = input.substring(start, end); System.out.println(match); } } catch (IOException e) { e.printStackTrace(); } catch (PatternSyntaxException e) { e.printStackTrace(); } }
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 . ja v a2s . 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()); } }
From source file:de.zazaz.iot.bosch.indego.util.IndegoMqttAdapter.java
public static void main(String[] args) { System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-normal.xml"); Options options = new Options(); StringBuilder commandList = new StringBuilder(); for (DeviceCommand cmd : DeviceCommand.values()) { if (commandList.length() > 0) { commandList.append(", "); }// w w w. j av a 2 s . c o m commandList.append(cmd.toString()); } options.addOption(Option // .builder("c") // .longOpt("config") // .desc("The configuration file to use") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("d") // .longOpt("debug") // .desc("Logs more details") // .build()); options.addOption(Option // .builder("?") // .longOpt("help") // .desc("Prints this help") // .build()); CommandLineParser parser = new DefaultParser(); CommandLine cmds = null; try { cmds = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); System.err.println(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(IndegoMqttAdapter.class.getName(), options); System.exit(1); return; } if (cmds.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); return; } if (cmds.hasOption("d")) { System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-debug.xml"); } String configFileName = cmds.getOptionValue('c'); File configFile = new File(configFileName); if (!configFile.exists()) { System.err.println(String.format("The specified config file (%s) does not exist", configFileName)); System.err.println(); System.exit(2); return; } Properties properties = new Properties(); try (InputStream in = new FileInputStream(configFile)) { properties.load(in); } catch (IOException ex) { System.err.println(ex.getMessage()); System.err.println(String.format("Was not able to load the properties file (%s)", configFileName)); System.err.println(); } MqttIndegoAdapterConfiguration config = new MqttIndegoAdapterConfiguration(); config.setIndegoBaseUrl(properties.getProperty("indego.mqtt.device.base-url")); config.setIndegoUsername(properties.getProperty("indego.mqtt.device.username")); config.setIndegoPassword(properties.getProperty("indego.mqtt.device.password")); config.setMqttBroker(properties.getProperty("indego.mqtt.broker.connection")); config.setMqttClientId(properties.getProperty("indego.mqtt.broker.client-id")); config.setMqttUsername(properties.getProperty("indego.mqtt.broker.username")); config.setMqttPassword(properties.getProperty("indego.mqtt.broker.password")); config.setMqttTopicRoot(properties.getProperty("indego.mqtt.broker.topic-root")); config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.mqtt.polling-interval-ms"))); MqttIndegoAdapter adapter = new MqttIndegoAdapter(config); adapter.startup(); }