List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
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 av a 2s .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:OCRRestAPI.java
public static void main(String[] args) throws Exception { /*//w w w . j a v 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//from w ww . ja va2 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 ww.jav a 2 s . com 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 {/* ww w . j ava2s.c o 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:ru.apertum.qsystem.client.forms.FAdmin.java
/** * @param args the command line arguments * @throws Exception/*from ww w. j a v a2 s . c o m*/ */ public static void main(String args[]) throws Exception { QLog.initial(args, 3); Locale.setDefault(Locales.getInstance().getLangCurrent()); //? ? , ? final Thread tPager = new Thread(() -> { FAbout.loadVersionSt(); String result = ""; try { final URL url = new URL(PAGER_URL + "/qskyapi/getpagerdata?qsysver=" + FAbout.VERSION_); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Java bot"); conn.connect(); final int code = conn.getResponseCode(); if (code == 200) { try (BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf8"))) { String inputLine; while ((inputLine = in.readLine()) != null) { result += inputLine; } } } conn.disconnect(); } catch (Exception e) { System.err.println("Pager not enabled. " + e); return; } final Gson gson = GsonPool.getInstance().borrowGson(); try { final Answer answer = gson.fromJson(result, Answer.class); forPager = answer; if (answer.getData().size() > 0) { forPager.start(); } } catch (Exception e) { System.err.println("Pager not enabled but working. " + e); } finally { GsonPool.getInstance().returnGson(gson); } }); tPager.setDaemon(true); tPager.start(); Uses.startSplash(); // plugins Uses.loadPlugins("./plugins/"); // ?. FLogin.logining(QUserList.getInstance(), null, true, 3, FLogin.LEVEL_ADMIN); Uses.showSplash(); java.awt.EventQueue.invokeLater(() -> { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager .getInstalledLookAndFeels()) { System.out.println(info.getName()); /*Metal Nimbus CDE/Motif Windows Windows Classic //GTK+*/ if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } if ("/".equals(File.separator)) { final FontUIResource f = new FontUIResource(new Font("Serif", Font.PLAIN, 10)); final Enumeration<Object> keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { final Object key = keys.nextElement(); final Object value = UIManager.get(key); if (value instanceof FontUIResource) { final FontUIResource orig = (FontUIResource) value; final Font font1 = new Font(f.getFontName(), orig.getStyle(), f.getSize()); UIManager.put(key, new FontUIResource(font1)); } } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } try { form = new FAdmin(); if (forPager != null) { forPager.showData(false); } else { form.panelPager.setVisible(false); } form.setVisible(true); } catch (Exception ex) { QLog.l().logger().error(" ? ?? . ", ex); } finally { Uses.closeSplash(); } }); }
From source file:Main.java
protected static InputStream getInputStream(String path) throws IOException { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); return connection.getInputStream(); }
From source file:Main.java
public static Bitmap readBitmap(HttpURLConnection response) { try {/* w w w .j ava 2s .c o m*/ return readBitmap(response.getInputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:Main.java
public static Bitmap getBitmap(String path) { try {/*from w w w . java2s. c o m*/ URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream is = conn.getInputStream(); return BitmapFactory.decodeStream(is); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:ProxyAuthenticator.java
private static void downloadFromUrl(String urlString) throws Exception { InputStream is = null;/* w w w . j a v a2s .com*/ FileOutputStream fos = null; URL url = new URL(urlString); System.out.println("Reading..." + url); Authenticator.setDefault(new ProxyAuthenticator("username", "password")); SocketAddress addr = new InetSocketAddress("your proxyserver ip address", 80); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy); is = conn.getInputStream(); String filename = getOutputFileName(url); fos = new FileOutputStream(filename); byte[] readData = new byte[1024]; int i = is.read(readData); while (i != -1) { fos.write(readData, 0, i); i = is.read(readData); } System.out.println("Created file: " + filename); System.out.println("Completed"); }