List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:inf.ufg.br.muralufg.features.push.GcmSender.java
public static void main(String[] args) { if (args.length < 1 || args.length > 2 || args[0] == null) { Log.d("", "usage: ./gradlew run -Pargs=\"MESSAGE[,DEVICE_TOKEN]\""); Log.d("", "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); Log.d("", "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pargs=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pargs=\"<Your_Message>\""); Log.d("", "Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pargs=\"<Your_Message>,<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pargs=\"<Your_Message>,<Your_Token>\""); System.exit(1);/* w w w. ja v a2s. c o m*/ } try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", args[0].trim()); // Where to send GCM message. if (args.length > 1 && args[1] != null) { jGcmData.put("to", args[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); Log.d("", resp); Log.d("", "Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { Log.d("", "Unable to send GCM message."); Log.d("", "Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); Log.d("", "", e); } catch (JSONException e) { Log.d("", "", e); } }
From source file:com.pp.dcasajus.forkpoint.GcmSender.java
public static void main(String[] args) { if (args.length < 1 || args.length > 2 || args[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println(//from w w w. j a va 2 s . com "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", args[0].trim()); // Where to send GCM message. if (args.length > 1 && args[1] != null) { jGcmData.put("to", args[1].trim()); } else { jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.jixstreet.temanusaha.gcm.GcmSender.java
public static void main(String[] args) { if (args.length < 1 || args.length > 2 || args[0] == null) { System.err.println("usage: ./gradlew run -Pmsg=\"MESSAGE\" [-Pto=\"DEVICE_TOKEN\"]"); System.err.println(""); System.err.println(/* ww w .j av a 2 s.co m*/ "Specify a test message to broadcast via GCM. If a device's GCM registration token is\n" + "specified, the message will only be sent to that device. Otherwise, the message \n" + "will be sent to all devices subscribed to the \"global\" topic."); System.err.println(""); System.err.println( "Example (Broadcast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\""); System.err.println(""); System.err.println("Example (Unicast):\n" + "On Windows: .\\gradlew.bat run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\"\n" + "On Linux/Mac: ./gradlew run -Pmsg=\"<Your_Message>\" -Pto=\"<Your_Token>\""); System.exit(1); } try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); try { jData.put("message", args[0].trim()); } catch (JSONException e) { e.printStackTrace(); } // Where to send GCM message. if (args.length > 1 && args[1] != null) { try { jGcmData.put("to", args[1].trim()); } catch (JSONException e) { e.printStackTrace(); } } else { try { jGcmData.put("to", "/topics/global"); } catch (JSONException e) { e.printStackTrace(); } } // What to send in GCM message. try { JSONObject data = jGcmData.put("data", jData); } catch (JSONException e) { e.printStackTrace(); } // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + API_KEY); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); System.out.println(resp); System.out.println("Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (IOException e) { System.out.println("Unable to send GCM message."); System.out.println("Please ensure that API_KEY has been replaced by the server " + "API key, and that the device's registration token is correct (if specified)."); e.printStackTrace(); } }
From source file:net.securnetwork.itebooks.downloader.EbookDownloader.java
/** * Program main method./*from www . j a v a 2s. c om*/ * * @param args the program arguments */ public static void main(String[] args) { if (validateArguments(args)) { int start = MIN_EBOOK_INDEX; int end = getLastEbookIndex(); String destinationFolder = null; // Check if resume mode if (args.length == 1 && args[0].equals(RESUME_ARG)) { start = Integer.parseInt(prefs.get(LAST_SAVED_EBOOK_PREF, MIN_EBOOK_INDEX - 1 + "")) + 1; //$NON-NLS-1$ destinationFolder = prefs.get(OUTPUT_FOLDER_PREF, null); } else { destinationFolder = getDestinationFolder(args); } if (destinationFolder == null) { System.err.println(Messages.getString("EbookDownloader.NoDestinationFolderFound")); //$NON-NLS-1$ return; } else { // Possibly fix the destination folder path destinationFolder = destinationFolder.replace("\\", "/"); if (!destinationFolder.endsWith("/")) { destinationFolder += "/"; } prefs.put(OUTPUT_FOLDER_PREF, destinationFolder); } if (args.length == 3) { start = getStartIndex(args); end = getEndIndex(args); } try { for (int i = start; i <= end; i++) { String ebookPage = BASE_EBOOK_URL + i + SLASH; Source sourceHTML = new Source(new URL(ebookPage)); List<Element> allTables = sourceHTML.getAllElements(HTMLElementName.TABLE); Element detailsTable = allTables.get(0); // Try to build an info bean for the ebook String bookTitle = EbookPageParseUtils.getTitle(detailsTable); if (bookTitle != null) { EbookInfo ebook = createEbookInfo(bookTitle, i, detailsTable); String filename = destinationFolder + Misc.getValidFilename(ebook.getTitle(), ebook.getSubTitle(), ebook.getYear(), ebook.getFileFormat()); System.out.print(MessageFormat.format(Messages.getString("EbookDownloader.InfoDownloading"), //$NON-NLS-1$ new Object[] { ebook.getSiteId() })); try { URL ebookPageURL = new URL(ebook.getDownloadLink()); HttpURLConnection con = (HttpURLConnection) ebookPageURL.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Referer", ebookPage); InputStream conIS = con.getInputStream(); FileUtils.copyInputStreamToFile(conIS, new File(filename)); System.out.println(Messages.getString("EbookDownloader.DownloadingOK")); //$NON-NLS-1$ prefs.put(LAST_SAVED_EBOOK_PREF, i + ""); //$NON-NLS-1$ conIS.close(); } catch (Exception e) { System.out.println(Messages.getString("EbookDownloader.DownloadingKO")); //$NON-NLS-1$ } } } } catch (Exception e) { System.err.println(Messages.getString("EbookDownloader.FatalError")); //$NON-NLS-1$ e.printStackTrace(); } } else { printHelp(); } }
From source file:OCRRestAPI.java
public static void main(String[] args) throws Exception { /*//from w w w .j av a 2 s.c o m Sample project for OCRWebService.com (REST API). Extract text from scanned images and convert into editable formats. Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code */ // Provide your user name and license code String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D"; String user_name = "FERGOID"; /* You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide Input parameters: [language] - Specifies the recognition language. This parameter can contain several language names separated with commas. For example "language=english,german,spanish". Optional parameter. By default:english [pagerange] - Enter page numbers and/or page ranges separated by commas. For example "pagerange=1,3,5-12" or "pagerange=allpages". Optional parameter. By default:allpages [tobw] - Convert image to black and white (recommend for color image and photo). For example "tobw=false" Optional parameter. By default:false [zone] - Specifies the region on the image for zonal OCR. The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. This parameter can contain several zones separated with commas. For example "zone=0:0:100:100,50:50:50:50" Optional parameter. [outputformat] - Specifies the output file format. Can be specified up to two output formats, separated with commas. For example "outputformat=pdf,txt" Optional parameter. By default:doc [gettext] - Specifies that extracted text will be returned. For example "tobw=true" Optional parameter. By default:false [description] - Specifies your task description. Will be returned in response. Optional parameter. !!!! For getting result you must specify "gettext" or "outputformat" !!!! */ // Build your OCR: // Extraction text with English language String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true"; // Extraction text with English and German language using zonal OCR ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400"; // Convert first 5 pages of multipage document into doc and txt // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt"; // Full path to uploaded document String filePath = "sarah-morgan.jpg"; byte[] fileContent = Files.readAllBytes(Paths.get(filePath)); URL url = new URL(ocrURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes())); // Specify Response format to JSON or XML (application/json or application/xml) connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length)); int httpCode; try (OutputStream stream = connection.getOutputStream()) { // Send POST request stream.write(fileContent); stream.close(); } catch (Exception e) { System.out.println(e.toString()); } httpCode = connection.getResponseCode(); System.out.println("HTTP Response code: " + httpCode); // Success request if (httpCode == HttpURLConnection.HTTP_OK) { // Get response stream String jsonResponse = GetResponseToString(connection.getInputStream()); // Parse and print response from OCR server PrintOCRResponse(jsonResponse); } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("OCR Error Message: Unauthorizied request"); } else { // Error occurred String jsonResponse = GetResponseToString(connection.getErrorStream()); JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse); // Error message System.out.println("Error Message: " + jsonObj.get("ErrorMessage")); } connection.disconnect(); }
From source file:bluevia.examples.MODemo.java
/** * @param args/* www.j a v a 2 s. c o m*/ */ public static void main(String[] args) throws IOException { BufferedReader iReader = null; String apiDataFile = "API-AccessToken.ini"; String consumer_key; String consumer_secret; String registrationId; OAuthConsumer apiConsumer = null; HttpURLConnection request = null; URL moAPIurl = null; Logger logger = Logger.getLogger("moSMSDemo.class"); int i = 0; int rc = 0; Thread mThread = Thread.currentThread(); try { System.setProperty("debug", "1"); iReader = new BufferedReader(new FileReader(apiDataFile)); // Private data: consumer info + access token info + phone info consumer_key = iReader.readLine(); consumer_secret = iReader.readLine(); registrationId = iReader.readLine(); // Set up the oAuthConsumer while (true) { try { logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages...")); apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret); apiConsumer.setMessageSigner(new HmacSha1MessageSigner()); moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId + "/messages?version=v1&alt=json"); request = (HttpURLConnection) moAPIurl.openConnection(); request.setRequestMethod("GET"); apiConsumer.sign(request); StringBuffer doc = new StringBuffer(); BufferedReader br = null; rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line = br.readLine(); while (line != null) { doc.append(line); line = br.readLine(); } System.out.printf("Output message: %s\n", doc.toString()); try { JSONObject apiResponse1 = new JSONObject(doc.toString()); String aux = apiResponse1.getString("receivedSMS"); if (aux != null) { String szMessage; String szOrigin; String szDate; JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS"); JSONArray smsInfo = smsPool.optJSONArray("receivedSMS"); if (smsInfo != null) { for (i = 0; i < smsInfo.length(); i++) { szMessage = smsInfo.getJSONObject(i).getString("message"); szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress") .getString("phoneNumber"); szDate = smsInfo.getJSONObject(i).getString("dateTime"); System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin, szMessage); } } else { JSONObject sms = smsPool.getJSONObject("receivedSMS"); szMessage = sms.getString("message"); szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber"); szDate = sms.getString("dateTime"); System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin, szMessage); } } } catch (JSONException e) { System.err.println("JSON error: " + e.getMessage()); } } else if (rc == HttpURLConnection.HTTP_NO_CONTENT) System.out.printf("No content\n"); else System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage()); request.disconnect(); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } mThread.sleep(15000); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } }
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 {//from w w w .j a va 2 s . c o m 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:SheetStructure.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. try {//from ww w . ja va 2 s. co m System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale..."); //First Create a new sheet. String sheetName = "Betty's Bake Sale"; //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON. //Their structure directly relates to the JSON that gets passed through the API. //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out. Sheet newSheet = new Sheet(); newSheet.setName(sheetName); newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null), new Column("Baker", "CONTACT_LIST", null, null, null), new Column("Price Per Item", "TEXT_NUMBER", null, null, null), new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST", null, null, Arrays.asList("Started", "Finished", "Delivered")))); connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); newSheet = newSheetResult.getResult(); System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId()); //Now add a column: String columnName = "Delivery Date"; System.out.println("Adding column " + columnName + " to " + sheetName); Column newColumn = new Column(columnName, "DATE", 5); connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newColumn); Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Column>>() { }); System.out.println( "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName()); //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it. System.out.println("Fetching " + newSheet.getName() + " sheet columns..."); connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); List<Column> allColumns = mapper.readValue(connection.getInputStream(), new TypeReference<List<Column>>() { }); System.out.println("Fetched."); //Now we will be adding rows System.out.println("Inserting rows into " + newSheet.getName()); List<Row> rows = new ArrayList<Row>(); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"), new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"), new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"), new Cell(allColumns.get(5).id, "2013-09-04")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"), new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Started")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"), new Cell(allColumns.get(1).id, "sandrassmart@example.com"), new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Finished")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"), new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"), new Cell(allColumns.get(5).id, "2013-09-05")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"), new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created. RowWrapper rowWrapper = new RowWrapper(); rowWrapper.setToBottom(true); rowWrapper.setRows(rows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName()); //Move a row to the top. System.out.println("Moving row 6 to the top."); RowWrapper moveToTop = new RowWrapper(); moveToTop.setToTop(true); connection = (HttpURLConnection) new URL( ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection(); connection.setRequestMethod("PUT"); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), moveToTop); mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Row 6 moved to top."); //Insert empty rows for spacing rows = new ArrayList<Row>(); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered")))); rowWrapper = new RowWrapper(); rowWrapper.setToBottom(true); rowWrapper.setRows(rows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName()); //Move Delivered rows to be children of the last spacer row. System.out.println("Moving delivered rows to Delivered section..."); Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(), newRowsResult.result.get(4).getId() }; RowWrapper parentRowLocation = new RowWrapper(); parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId()); for (Long deliveredId : deliveredRowIds) { System.out.println("Moving " + deliveredId + " to Delivered."); connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection(); connection.setRequestMethod("PUT"); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), parentRowLocation); mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Row id " + deliveredId + " moved."); } System.out.println("Appending additional rows to items in progress..."); List<Row> siblingRows = new ArrayList<Row>(); siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"), new Cell(allColumns.get(1).id, "tomlively@example.com"), new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished")))); siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"), new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started")))); rowWrapper = new RowWrapper(); rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId()); rowWrapper.setRows(siblingRows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName()); System.out.println("Moving Status column to index 1..."); Column statusColumn = allColumns.get(4); Column moveColumn = new Column(); moveColumn.setIndex(1); moveColumn.setTitle(statusColumn.title); moveColumn.setSheetId(newSheet.getId()); moveColumn.setType(statusColumn.getType()); connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); connection.setRequestMethod("PUT"); mapper.writeValue(connection.getOutputStream(), moveColumn); Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Column>>() { }); System.out.println("Moved column " + movedColumnResult.getResult().getId()); System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale."); } catch (IOException e) { InputStream is = ((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:Main.java
private static HttpURLConnection getConnection(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true);//from w w w . ja v a 2 s. c o m conn.setDoOutput(true); conn.setRequestProperty("Accept", "text/xml"); return conn; }
From source file:Main.java
public static void setUpConnection(HttpURLConnection connection, String method) { try {// ww w. j av a 2 s . c o m connection.setRequestMethod(method); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); } catch (ProtocolException e) { e.printStackTrace(); } }